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

前端 未结 12 1026
[愿得一人]
[愿得一人] 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 03:57
        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

    0 讨论(0)
  • 2020-12-08 03:58

    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); 
    }
    
    0 讨论(0)
  • 2020-12-08 03:59

    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

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-08 04:07

    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));
    
    0 讨论(0)
  • 2020-12-08 04:07

    This works pretty well

    var price=99.012334554
    price = price.roundTodouble();
    print(price); // 99.01
    
    0 讨论(0)
提交回复
热议问题