問題描述
float 數(shù)據(jù)類型是單精度 32 位 IEEE 754 浮點(diǎn)數(shù),double 數(shù)據(jù)類型是雙精度 64 位 IEEE 754 浮點(diǎn)數(shù).
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.
這是什么意思?我什么時(shí)候應(yīng)該使用 float 而不是 double 或反之亦然?
What does it mean? And when should I use float instead of double or vice-versa?
推薦答案
維基百科頁面這是一個(gè)很好的起點(diǎn).
總結(jié)一下:
float
用 32 位表示,有 1 個(gè)符號(hào)位、8 位指數(shù)和 23 位有效數(shù)字(或從科學(xué)記數(shù)法數(shù)得出的數(shù)字: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 個(gè)符號(hào)位、11 位指數(shù)和 52 位有效位.
double
is represented in 64 bits, with 1 sign bit, 11 bits of exponent, and 52 bits of significand.
默認(rèn)情況下,Java 使用 double
來表示它的浮點(diǎn)數(shù)(所以文字 3.14
的類型是 double
).它也是可以為您提供更大數(shù)字范圍的數(shù)據(jù)類型,因此我強(qiáng)烈建議使用它而不是 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
.
可能有某些庫實(shí)際上會(huì)強(qiáng)制您使用 float
,但總的來說 - 除非您可以保證您的結(jié)果足夠小以適合 float
's 規(guī)定范圍,那么最好選擇與 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
.
如果您需要準(zhǔn)確性 - 例如,您不能有不準(zhǔn)確的十進(jìn)制值(例如 1/10 + 2/10
),或者您正在做任何事情 與貨幣(例如,在系統(tǒng)中表示 $10.33),然后使用 BigDecimal
,它可以支持任意數(shù)量的精度并優(yōu)雅地處理此類情況.
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.
這篇關(guān)于Java中的浮點(diǎn)和雙精度數(shù)據(jù)類型的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!