Reputation: 51
I couldn't find a way to round double to 2 decimal places and remove trailing zeros in Dart. I found a way to round but it doesn't work if I try to truncate trailing zero.
Here is what I am trying to do:
double x = 5.0;
double y = 9.25843223423423;
double z = 10.10;
print(x); //Expected output --> 5
print(y); //Expected output --> 9.26
print(z); //Expected output --> 10.1
EDIT:
I found a way to solve the first 2 print statements above. I thought I should add it for whoever is searching it.
String getFormattedNumber( num ) {
var result;
if(num % 1 == 0) {
result = num.toInt();
} else {
result = num.toStringAsFixed(2);
}
return result.toString();
}
Upvotes: 3
Views: 9804
Reputation: 793
I think a better way is using the Flutter maths
library.
// ROUND NUMBERS TO 2 DECIMAL PLACES
double roundNumber(double value, int places) {
num val = pow(10.0, places);
return ((value * val).round().toDouble() / val);
}
This function would help you do for any decimal place you want.
Then you can use it this way:
double num1 = roundNumber(12.334456789, 2);
print(num1);
should print:
: 12.33
Upvotes: 0
Reputation: 89985
Rounding a floating point number according to a decimal representation doesn't make much sense since many decimal fractions (such as 0.3
) can't be exactly represented by floating point numbers anyway. (This is inherent to all floating point numbers and is not specific to Dart.)
You can, however, try to make string representations of your number pretty. num.toStringAsFixed
rounds to the specified number of fractional digits. From there, you can use a regular expression to remove trailing zeroes:
String prettify(double d) =>
// toStringAsFixed guarantees the specified number of fractional
// digits, so the regular expression is simpler than it would need to
// be for more general cases.
d.toStringAsFixed(2).replaceFirst(RegExp(r'\.?0*$'), '');
double x = 5.0;
double y = 9.25843223423423;
double z = 10.10;
print(prettify(x)); // Prints: 5
print(prettify(y)); // Prints: 9.26
print(prettify(z)); // Prints: 10.1
print(prettify(0)); // Prints: 0
print(prettify(1)); // Prints: 1
print(prettify(200); // Prints: 200
Also see How to remove trailing zeros using Dart.
Upvotes: 9
Reputation: 7492
Here is sample code what you want.
multiply by 10^(count of number after point)
if count of number after point is 2
9.25843223423423 -> 925.843223423423
round 1)'s result
925.843223423423 -> 926
divide by 10^(count of number after point)
926 -> 9.26
import 'dart:math';
void main() {
double x = 0.99;
double y = 9.25843223423423;
double z = 10.10;
print(x); //Expected output --> 5
print(y); //Expected output --> 9.26
print(z); //Expected output --> 10.1
print(customRound(x, 2));
print(customRound(y, 2));
print(customRound(z, 2));
for(var i = 0.01 ; i < 1 ; i += 0.01) {
print(customRound(i, 2));
}
}
dynamic customRound(number, place) {
var valueForPlace = pow(10, place);
return (number * valueForPlace).round() / valueForPlace;
}
Upvotes: 2