Skip to content

Instantly share code, notes, and snippets.

@shmink
Created June 18, 2024 15:47
Show Gist options
  • Save shmink/e8ab76b086cbd79b212491b38bf58a7f to your computer and use it in GitHub Desktop.
Save shmink/e8ab76b086cbd79b212491b38bf58a7f to your computer and use it in GitHub Desktop.
dart truncate a double
void main() {
double original = 116.41666666;
print('off by one ${original.toStringAsFixed(2)}');
// This is an issue especially when trying to display money
double truncateAsFixed(double value, int remainder) {
var integer = value.toInt();
// To get the remainder on it's own and trim down
var decimals = (value - integer).toString().substring(1, 2 + remainder);
// Form a string of the two before return
var stringRepresentation = '${integer.toString()}$decimals';
return double.parse(stringRepresentation);
}
print('truncated to 2 decimal places ${truncateAsFixed(original, 2)}');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment