用正确的小数位数格式化数字 [英] Formatting a number with correct decimal scale

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

问题描述

我需要格式化一个小数点后2位的数字.原始数字可以是整数,也可以是小数点后三位的数字.但是,无论原始数字是整数还是小数位,结果的格式都应设置为逗号且始终保留小数点后两位.

I need to format a number with scale of 2 decimal places. The original number may be a whole number or a number with three decimal places. However the result should be formatted to have commas and also two decimal places always regardless of whether the original number is whole number or having decimal places.

  1. 当原始数字= 56565656.342 ==>我需要56,565,656.34
  2. 当原始数字= 56565656 ==>我需要56,565,656.00
  3. 当原始数字= 56565656.7 ==>我需要56,565,656.70

我正在使用下面的代码来格式化代码,但未能在上述2&中添加两位小数. 3例.

I am using the following code which is formatting the code but its failing to add the two decimal places in the above 2 & 3 cases.

String originalNumber = "56565656.7";
BigDecimal b = new BigDecimal(originalNumber).setScale(2, BigDecimal.ROUND_HALF_UP);
String formattedNumber = NumberFormat.getInstance().format(b);

请让我知道是否有任何方法可以通过efficeint方式完成此任务.

Please let me know if there is any way to accomplish this in efficeint way.

谢谢.

推荐答案

看看或者,您可以 setScale 方法.

        BigDecimal bg1 = new BigDecimal("56565656.342");
        BigDecimal bg2 = new BigDecimal("56565656.00");
        BigDecimal bg3 = new BigDecimal("56565656.70");

        DecimalFormat df = new DecimalFormat("###,###.00");
        System.out.println(df.format(bg1.doubleValue()));
        System.out.println(df.format(bg2.doubleValue()));
        System.out.println(df.format(bg3.doubleValue()));

        System.out.println(bg1.setScale(2, BigDecimal.ROUND_HALF_UP));
        System.out.println(bg2.setScale(2, BigDecimal.ROUND_HALF_UP));
        System.out.println(bg3.setScale(2, BigDecimal.ROUND_HALF_UP));

收益:

56,565,656.34
56,565,656.00
56,565,656.70
56565656.34
56565656.00
56565656.70

还忘了提及:如果您追求精度,我建议您使用setScale方法,使用.doubleValue()方法将产生double,这可能会导致精度降低.

Also forgot to mention: If you are after precision, I would recommend you use the setScale method, using the .doubleValue() method will yield a double which can cause loss of precision.

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

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