2015-02-09 226 views
7

給定一個雙精度值,我想將它舍入到小數點後的精度點,類似於PHP的round()函數。如何在Dart中將小數點後面的雙精度加倍到精確的精確度?

我可以在飛鏢文檔找到最接近的事是double.toStringAsPrecision(),但是這並不完全符合我需要的,因爲它包括數字前在精度總點數的小數點。

例如,使用toStringAsPrecision(3):

0.123456789 rounds to 0.123 
9.123456789 rounds to 9.12 
98.123456789 rounds to 98.1 
987.123456789 rounds to 987 
9876.123456789 rounds to 9.88e+3 

AS號的幅度增加,我相應的小數點後失去精度。

回答

4
void main() { 
    int decimals = 2; 
    int fac = pow(10, decimals); 
    double d = 1.234567889; 
    d = (d * fac).round()/fac; 
    print("d: $d"); 
} 

打印: 1.23

+0

這是目前最好的做這個。舍入到像0.01這樣的精度本身不是一個雙精度值,這不是微不足道的。結果可能甚至不能表現爲雙倍。我強烈建議在小數精度很重要的地方使用整數(例如金錢)。 – lrn 2015-02-10 18:16:17

+1

另外值得指出的是,如果編譯爲js,那麼Dart整數也將開始失去精度,您需要使用如下包:https://pub.dartlang.org/packages/bignum – 2015-02-10 22:03:55

10

請參閱該文檔爲num.toStringAsFixed()

字符串toStringAsFixed(INT參數fractionDigits)

返回此十進制點串的表示。

在計算字符串表示之前,將其轉換爲double。

如果該絕對值大於或等於10^21則此方法返回由this.toStringAsExponential計算的指數表示()。否則,結果是最接近的字符串表示形式,精確到小數點後的分數位數。如果fractionDigits等於0,則省略小數點。

參數參數fractionDigits必須是令人滿意的整數:0 < =參數fractionDigits < = 20。

實例:

1.toStringAsFixed(3); // 1.000 
(4321.12345678).toStringAsFixed(3); // 4321.123 
(4321.12345678).toStringAsFixed(5); // 4321.12346 
123456789.toStringAsFixed(3); // 123456789.000 
1000000000000000000000.toStringAsFixed(3); // 1e+21 
5.25.toStringAsFixed(0); // 5 
2

num.toStringAsFixed()輪。這一個將你的num(n)轉換成你想要的小數位數(2)的字符串,然後在一行代碼中分析回你的num:

n = num.parse(n.toStringAsFixed(2));