简体   繁体   English

如何检查Double是否具有Java舍入?

[英]How to check if a Double has java rounding?

Is there anyway to check if a Double has java rounding eg -260.01079999999996 无论如何,是否要检查Double是否具有Java舍入,例如-260.01079999999996

I have one system that passes a computed Double value. 我有一个系统传递经过计算的Double值。 By right should be -260.0108. 正确的应该是-260.0108。

When using floats and doubles, the "issues" with rounding are due to the limitations of digital computers. 当使用浮点数和双精度数时,由于数字计算机的限制,带有四舍五入的“问题”是造成的。

If you don't want rounding, use integers. 如果不想舍入,请使用整数。 If you need to save a number with a fixed number of digits after comma, use a BigDecimal ; 如果您需要在逗号后保存一个固定位数的数字,请使用BigDecimal or always round your double at Xth digit after comma; 或始终在逗号后的第X个数字处将双精度取整; or use the number as integer while dividing or multiplying it by 10^n before showing in view (elaboration below). 或使用数字作为整数,然后将其除以10^n或乘以10n,然后再显示在视图中(下面详述)。

For example, you could save -2600108 as integer and a factor 1000 . 例如,您可以将-2600108保存为整数,并保存为1000 Addition, subtraction, multiplication and saving work flawlessly and without side-effects in this case. 加法,减法,乘法和保存工作完美无缺,在这种情况下没有副作用。 Division needs doubles though. 分裂需要加倍。

If you know from external evidence that the exact answer at a certain point in your code must be an integer, round to nearest integer there. 如果您从外部证据中知道代码中特定点的确切答案必须是整数,则四舍五入到最接近的整数。

Otherwise, you get the most accurate double result by carrying the full precision through your calculations, using DecimalFormat to print only the meaningful digits. 否则,通过使用DecimalFormat仅打印有意义的数字来进行计算,从而获得最高精度的双精度结果。

There is nothing special about "java rounding". “ java舍入”没有什么特别的。 The special thing is that the default output preserves enough digits to uniquely identify the double. 特殊的是,默认输出保留足够的数字以唯一标识双精度型。 Many other languages, by default, round to fewer digits, losing accuracy but making results look tidier. 默认情况下,许多其他语言舍入到较少的数字,虽然准确性下降,但结果看起来更整齐。

Using BigDecimal is a major win if every number in the calculation can be exactly represented as a short decimal fraction. 如果计算中的每个数字都可以精确地表示为短小数部分,那么使用BigDecimal是一个重大胜利。 That often happens for currency calculations. 货币计算通常会发生这种情况。 However, as soon as you hit a fraction such as 1/3 that cannot be exactly represented by any finite number of decimal digits, you have to deal with rounding error anyway. 但是,一旦您击中了诸如1/3之类的分数,而该分数不能由任何有限数量的十进制数字精确表示,则无论如何都必须处理舍入误差。 For many financial calculations, there are fixed rules for rounding. 对于许多财务计算,都有固定的四舍五入规则。

In theory, BigDecimal could also be used to get extra precision, but that is rarely practical. 从理论上讲,BigDecimal也可以用于获得额外的精度,但这很少实用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM