Given a double, I want to round it to a given number of points of precision after the decimal point, similar to PHP\'s round() function.
The closest thing I
var price=99.012334554;
price = price.toStringAsFixed(2);
print(price); // 99.01
That is the ref of dart. ref: https://api.dartlang.org/stable/2.3.0/dart-core/num/toStringAsFixed.html
Above solutions do not appropriately round numbers. I use:
double dp(double val, int places){
double mod = pow(10.0, places);
return ((val * mod).round().toDouble() / mod);
}
I used toStringAsFixed() method , to round number to specific numbers after the decimal point EX : double num = 22.48132906 and when I rounded to two numbers like this : print(num.toStringAsFixed(2) ;
it printed 22.48
and when I rounded to one number .. printed 22.5
Above solutions do not work for all cases. What worked for my problem was this solution that will round your number (0.5 to 1 or 0.49 to 0) and leave it without any decimals:
Input: 12.67
double myDouble = 12.67;
var myRoundedNumber; // Note the 'var' datatype
// Here I used 1 decimal. You can use another value in toStringAsFixed(x)
myRoundedNumber = double.parse((myDouble).toStringAsFixed(1));
myRoundedNumber = myRoundedNumber.round();
print(myRoundedNumber);
Output: 13
This link has other solutions too
num.toStringAsFixed() rounds. This one turns you num (n) into a string with the number of decimals you want (2), and then parses it back to your num in one sweet line of code:
n = num.parse(n.toStringAsFixed(2));
This works pretty well
var price=99.012334554
price = price.roundTodouble();
print(price); // 99.01