問題描述
float 數據類型是單精度 32 位 IEEE 754 浮點數,double 數據類型是雙精度 64 位 IEEE 754 浮點數.
The float data type is a single-precision 32-bit IEEE 754 floating point and the double data type is a double-precision 64-bit IEEE 754 floating point.
這是什么意思?我什么時候應該使用 float 而不是 double 或反之亦然?
What does it mean? And when should I use float instead of double or vice-versa?
推薦答案
維基百科頁面這是一個很好的起點.
總結一下:
float
用 32 位表示,有 1 個符號位、8 位指數和 23 位有效數字(或從科學記數法數得出的數字:2.33728*1012;33728 是有效位).
float
is represented in 32 bits, with 1 sign bit, 8 bits of exponent, and 23 bits of the significand (or what follows from a scientific-notation number: 2.33728*1012; 33728 is the significand).
double
用 64 位表示,有 1 個符號位、11 位指數和 52 位有效位.
double
is represented in 64 bits, with 1 sign bit, 11 bits of exponent, and 52 bits of significand.
默認情況下,Java 使用 double
來表示它的浮點數(所以文字 3.14
的類型是 double
).它也是可以為您提供更大數字范圍的數據類型,因此我強烈建議使用它而不是 float
.
By default, Java uses double
to represent its floating-point numerals (so a literal 3.14
is typed double
). It's also the data type that will give you a much larger number range, so I would strongly encourage its use over float
.
可能有某些庫實際上會強制您使用 float
,但總的來說 - 除非您可以保證您的結果足夠小以適合 float
's 規定范圍,那么最好選擇與 double
.
There may be certain libraries that actually force your usage of float
, but in general - unless you can guarantee that your result will be small enough to fit in float
's prescribed range, then it's best to opt with double
.
如果您需要準確性 - 例如,您不能有不準確的十進制值(例如 1/10 + 2/10
),或者您正在做任何事情 與貨幣(例如,在系統中表示 $10.33),然后使用 BigDecimal
,它可以支持任意數量的精度并優雅地處理此類情況.
If you require accuracy - for instance, you can't have a decimal value that is inaccurate (like 1/10 + 2/10
), or you're doing anything with currency (for example, representing $10.33 in the system), then use a BigDecimal
, which can support an arbitrary amount of precision and handle situations like that elegantly.
這篇關于Java中的浮點和雙精度數據類型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!