是否有一个Java数字格式库可以处理有效数字? [英] Is there a Java number formatting library that handles significant digits?

查看:56
本文介绍了是否有一个Java数字格式库可以处理有效数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内置的DecimalFormat仅允许您指定小数点右边的位数.

The built in DecimalFormat only allows you to specify number of digits to the right of the decimal place.

由于将数字表示为双精度的局限性,因此数字格式需要在其内部包含一定程度的舍入.在一般情况下,舍入必须为有效位数(默认情况下为双精度),否则格式化的双精度最终会显示3.5999999而不是3.6.

Because of the limitations of representing numbers as double, number formatting needs to include some level of rounding inside of it. In the general case, that rounding has to be to a number of significant digits (default case is the precision of a double) or else your formatted double will end up showing stuff like 3.5999999 instead of 3.6.

我能找到的最接近的解决方案是使用

The closest solution I could find is using

new BigDecimal(double, new MathContext(14, RoundingMode.HALF_EVEN).stripTrailingZeros().toPlainString()

但是,仅提供一种格式.如果我通常需要对其进行格式化(组分隔符,小数点分隔符,位数限制,填充等),则JDK库中没有任何内容.

however, that only provides a single format. If I need to format it generally (group separator, decimal separator, limit to number of digits, padding, etc.), there is nothing in the JDK library.

那里是否有一个通用的数字格式库,可以正确处理四舍五入到有效数字?

Is there a general number formatting library out there that will handle rounding to significant digits properly?

有人问例子.因此,假设我想将其格式化为4位有效数字,然后:

Someone asked for examples. So, let's say I wanted to format to 4 significant digits, then:

0.000003599999 -> 0.0000036
4.12345 -> 4.123
1234.345 -> 1234

我们将采用的一般方法是四舍五入到14位数字,因为根据具体情况,双精度数只能代表15-17位有效数字(或者我已经读过).

The general approach we would take would be to round to 14 digits since depending on the circumstances, a double can only represent around 15-17 significant digits anyway (or so I've read).

推荐答案

这会增加很多开销(大约5 MB),但是Unicode国际组件项目具有增强的DecimalFormat,可以很好地处理有效数字.

This adds a lot of overhead (5 MB or so), but the International Components for Unicode project has an enhanced DecimalFormat that handles significant digits nicely.

http://icu-project.org/apiref/icu4j/com/ibm/icu/text/DecimalFormat.html#sigdig

DecimalFormat formatter = new DecimalFormat();
formatter.setMaximumSignificantDigits( 4 );
System.out.println( formatter.format( hoursSinceLastAccident ) );

这篇关于是否有一个Java数字格式库可以处理有效数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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