How do you round a double in Dart to a given degree of precision AFTER the decimal point?

前端 未结 12 1076
[愿得一人]
[愿得一人] 2020-12-08 03:46

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

12条回答
  •  孤城傲影
    2020-12-08 04:05

    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

提交回复
热议问题