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

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

问题描述

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

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