返回或返回实例变量的小数。

huangapple go评论64阅读模式
英文:

Return or returning the decimal of the instance variable

问题

一个从字符串str(实例变量)的输入参数索引位置开始的部分字符串
如果输入参数索引位置大于等于字符串长度,则返回空字符串

英文:

a partial string that begins at input parameter index position of the String str (instance variable)
Returns empty string if the input parameter index position is larger than or equal to the string length

答案1

得分: 1

使用%求余操作符,除数为1,是获取double值的“小数部分”即数字的“小数位”的最简单方法,即:

public double drawDecimal() {
    return dD % 1;
}

这将出现与返回0.11000000000000032相同的问题,这是浮点数固有的不精确性所导致的效果。参见:Is floating point math broken?

为了解决这个问题,您可以使用BigDecimal进行相同的计算,即:

public double drawDecimal() {
    return BigDecimal.valueOf(dD).remainder(BigDecimal.ONE).doubleValue();
}

结果为0.11,保持了原始值的“小数精度”。

英文:

The easiest way to get the "decimals" of a double value, meaning the fractional digits of the number, is to use the % remainder operator with a divisor of 1, i.e.

public double drawDecimal() {
    return dD % 1;
}

That has the same problem with returning 0.11000000000000032, which is an effect of the inherent inaccuracy of floating-point numbers. See: Is floating point math broken?

To get around that, you could do the same calculation using BigDecimal, i.e.

public double drawDecimal() {
    return BigDecimal.valueOf(dD).remainder(BigDecimal.ONE).doubleValue();
}

The result is 0.11, keeping the "decimal precision" of the original value.

huangapple
  • 本文由 发表于 2020年9月22日 04:09:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63999339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定