在BigDecimal中修剪两个以上的尾随零 [英] Trim More than two trailing Zeros in BigDecimal

查看:142
本文介绍了在BigDecimal中修剪两个以上的尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为BigDecimal修剪两个以上尾随零的好方法

What would be a good way to trim more than two trailing zeros for a BigDecimal

所以1.2200会打印1.22而1.0000会打印1.00

So 1.2200 would print 1.22 and 1.0000 would print 1.00

编辑以及返回1.222200作为
1.2222和1.220000001作为1.220000001等。所以忽略前两个零我想修剪任何传入的0并且不修剪非零值

一种方法可能是乘法,然后应用内置的修剪尾随零,然后除以100.角落情况可能有问题,但值在我的问题是基于货币,永远不会超过Java设定的界限(否则它意味着我的软件正在处理以美元计价的出价)

One way could be to multiply, then apply the built in trim trailing zeros and then divide by 100. It could be problematic with corner cases but the values in my problem are currency based and would never exceed the bounds set by Java (or else it means my software is dealing with bids which are in gazzilions of dollars)

丑陋解决方案如下:

System.out.println(((new BigDecimal("1.230223000")
                                 .multiply(new BigDecimal("100.0"))
                                 .stripTrailingZeros()).divide(new BigDecimal("100.0"))));


推荐答案

检查一下,

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class DecimalFormatExample
{
  public static void main(String args[])
  {
  double amount = 2192.015;
  NumberFormat formatter = new DecimalFormat("#0.00");
  System.out.println("The Decimal Value is:"+formatter.format(amount));
  }
}  

这篇关于在BigDecimal中修剪两个以上的尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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