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

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

    To round a double in Dart to a given degree of precision AFTER the decimal point, you can use built-in solution in dart toStringAsFixed() method, but you have to convert it back to double

    void main() {
      double step1 = 1/3;  
      print(step1); // 0.3333333333333333
      
      String step2 = step1.toStringAsFixed(2); 
      print(step2); // 0.33 
      
      double step3 = double.parse(step2);
      print(step3); // 0.33
    }
    
    

提交回复
热议问题