为什么java中floatda正确_为什么cast to float在java中产生正确的结果?
文檔沒有特別好地解釋,但
Double.toString(double)基本上在它產生的輸出中執行一些舍入. Double.toString算法在整個Java SE中使用,包括例如System.out的PrintStream.println(double).文檔說明了這一點:
How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part,and beyond that as many,but only as many,more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is,suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x,then d must be one of them and the least significant bit of the significand of d must be 0.
換句話說,它表示toString的返回值不一定是參數的精確十進制表示.唯一的保證是(粗略地說)參數比任何其他雙值更接近返回值.
因此,當您執行類似System.out.println(1.10)和1.10的操作時,這并不意味著傳入的值實際上等于基數10值1.10.相反,基本上會發生以下情況:
>首先,在編譯期間,檢查文字1.10并舍入以產生最接近的double值. (它在JLS here中說,對此的規則例如在Double.valueOf(String)中詳細說明為double.)
>其次,當程序運行時,Double.toString生成一個十進制值的字符串表示形式,上一步生成的double值比任何其他double值更接近.
恰好在第二步中轉換為String通常會生成一個與第一步中的文字相同的String.我認為這是設計的.無論如何,文字,例如1.10不會產生一個精確等于1.10的雙精度值.
您可以使用BigDecimal(double)構造函數發現double(或float的實際值,因為它們總是可以放在double中):
When a double must be used as a source for a BigDecimal,note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result,use the static valueOf(double) method.
// 0.899999999999999911182158029987476766109466552734375
System.out.println(new BigDecimal((double) ( 2.00 - 1.10 )));
// 0.89999997615814208984375
System.out.println(new BigDecimal((float) ( 2.00 - 1.10 )));
你可以看到,結果都不是0.9.在這種情況下,Float.toString恰好產生0.9而Double.toString則不然,這或多或少只是巧合.
作為旁注,(雙)(2.00 – 1.10)是一個冗余演員. 2.00和1.10已經是雙重文字,因此評估表達式的結果已經是雙倍的.另外,要減去float,你需要轉換兩個操作數,如(float)2.00 – (float)1.10或使用浮動文字,如2.00f – 1.10f. (float)(2.00 – 1.10)僅將結果轉換為float.
總結
以上是生活随笔為你收集整理的为什么java中floatda正确_为什么cast to float在java中产生正确的结果?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: wan口有流量但电脑上不了网_wan口有
- 下一篇: android style边界显示兼容问