格式化十进制数 [英] Formatting Decimal Number

查看:147
本文介绍了格式化十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在格式化一个十进制数字,并且我有以下条件对其进行格式化:

I am formatting a decimal number and I have the following criteria to format it:


  • 该数字最多应为两个小数位( 10.1234 => 10.12

  • 如果小数点后只有一位,那么它将以额外的0结束( 10.5 => 10.50

  • 千位分隔符将是逗号( 12345.2345 => 12,345.23

  • Number should be at most two decimal places (10.1234=>10.12)
  • If there is only one digit after decimal then it will ends up with an extra 0 (10.5=>10.50)
  • Thousand separator will be comma (12345.2345 => 12,345.23)

我写了以下逻辑:

double x = Double.parseDouble(value.toString());
String dec = x % 1 == 0 ?  new java.text.DecimalFormat("###,###.##").format(x) : new java.text.DecimalFormat("###,###.00").format(x);

现在正在打印:

11111111111110.567=>11,111,111,111,110.57
111111111111110.567=>111,111,111,111,110.56
1111111111111110.567=>1,111,111,111,111,110.60
11111111111111110.567=>11,111,111,111,111,110
111111111111111110.567=>111,111,111,111,111,104
1111111111111111110.567=>1,111,111,111,111,111,170

我不明白行为为何会改变。我应如何将 1111111111111111110.567 打印为 1,111,111,111,111,111,110.57

I don't understand why the behavior changes. How should I print 1111111111111111110.567 as 1,111,111,111,111,111,110.57?

推荐答案

问题是,您不能一开始就完全像 double 那样代表1111111111111111110.567。 (您甚至无法准确表示最短的值,但随着幅度的增加,误差会大大增加。)

The problem is that you can't represent 1111111111111111110.567 exactly as a double in the first place. (You can't even represent your shortest value exactly, but the inaccuracy will increase significantly as you increase the magnitude.)

A double 仅有大约17位有效数据有效数字-您正试图获得22位数字。

A double only has about 17 significant digits of useful data anyway - you're trying to get 22 digits.

使用 BigDecimal 如果需要更高的精度-但请注意,这也会改变其他情况。无论如何,您想代表什么样的价值?自然值(权重,距离等)适用于 double ;人工值(尤其是货币值)适用于 BigDecimal

Use BigDecimal if you want more precision - but be aware that this will change other things too. What kind of value are you trying to represent, anyway? Natural values (weights, distances etc) are appropriate for double; artificial values (particularly currency values) are appropriate for BigDecimal.

这篇关于格式化十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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