java double 保留精度_在Java中保留精度为double

正如其他人所提到的,如果你想拥有11.4的精确表示,你可能想要使用

BigDecimal类。

现在,一点点解释为什么这种情况发生:

Java中的float和double基元类型是floating point数字,其中数字存储为分数和指数的二进制表示。

更具体地,双精度浮点值例如双精度值是64位值,其中:

> 1位表示符号(正或负)。

> 11位用于指数。

> 52位用于有效数字(小数部分为二进制)。

这些部分被组合以产生值的双重表示。

字节,char,int,long类型是fixed-point数字,它们是数字的精确表示。与固定点数不同,浮点数有时(安全假定“大部分时间”)无法返回数字的精确表示。这就是为什么你最终以11.399999999999作为5.6 5.8的结果的原因。

当需要一个精确的值(例如1.5或150.1005)时,您将需要使用一个定点类型,这将能够精确地表示数字。

正如已经提到过几次,Java有一个BigDecimal类,它将处理非常大的数字和非常小的数字。

从BigDecimal类的Java API参考:

Immutable,

arbitrary-precision signed decimal

numbers. A BigDecimal consists of an

arbitrary precision integer unscaled

value and a 32-bit integer scale. If

zero or positive, the scale is the

number of digits to the right of the

decimal point. If negative, the

unscaled value of the number is

multiplied by ten to the power of the

negation of the scale. The value of

the number represented by the

BigDecimal is therefore (unscaledValue

× 10^-scale).

Stack Overflow上有很多关于浮点数及其精度的问题。以下是可能感兴趣的相关问题的列表:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值