Java中的浮点数和double数据类型 [英] Float and double datatype in java

查看:188
本文介绍了Java中的浮点数和double数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浮点数据类型是单精度32位IEEE 754浮点数,双数据类型是双精度64位IEEE 754浮点数。



这是什么意思?何时应该使用float而不是double,反之亦然。

解决方案

是一个很好的开始。



总结: / p>


  • float 以32位表示,具有1个符号位,8指数的位和23位的有效位数(或从科学计数符号:2.33728 * 10 12 ; 33728是有效位数)。


  • double 以64位表示,具有1个符号位,11位指数和52位有效位数。




默认情况下,Java使用 double 表示其浮点数字(所以文字 3.14 键入 double )。这也是数据类型,它会给你一个更大的数字范围,所以我强烈建议使用 float



可能有某些库实际上强制您使用 float ,但一般情况下,除非您能保证您的结果足够小以适应 float 规定范围,那么最好选择使用 double



如果您需要准确性 - 例如,您不能具有不准确的十进制值(例如 1/10 + 2/10 ),或者您正在执行任何任何货币(例如,在系统中代表10.33美元),然后使用一个 BigDecimal ,它可以支持任意数量的精度,并处理优雅的情况。


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.

What does it mean? And when should I use float instead of double or vice-versa.

解决方案

The Wikipedia page on it is a good place to start.

To sum up:

  • 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 is represented in 64 bits, with 1 sign bit, 11 bits of exponent, and 52 bits of significand.

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.

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.

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中的浮点数和double数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆