Java中的浮点和双精度数据类型

Float and double datatype in Java(Java中的浮点和双精度数据类型)
本文介绍了Java中的浮点和双精度数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)