问题描述
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中的浮点和双精度数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!