Created
June 18, 2024 15:47
-
-
Save shmink/e8ab76b086cbd79b212491b38bf58a7f to your computer and use it in GitHub Desktop.
dart truncate a double
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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