Java BigDecimal 删除小数和尾随数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1316945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:10:39  来源:igfitidea点击:

Java BigDecimal remove decimal and trailing numbers

javadecimalbigdecimal

提问by Zero Cool

I'm new to Java and trying to take a BigDecimal (for example 99999999.99) and convert it to a string but without the decimal place and trailing numbers. Also, I don't want commas in the number and rounding is not needed.

我是 Java 新手,并尝试使用 BigDecimal(例如 99999999.99)并将其转换为字符串,但没有小数位和尾随数字。另外,我不想在数字中使用逗号,也不需要四舍五入。

I've tried:

我试过了:

Math.Truncate(number)

but BigDecimal is not supported.

但不支持 BigDecimal。

Any ideas?

有任何想法吗?

Thanks very much.

非常感谢。

采纳答案by David Z

Try number.toBigInteger().toString()

尝试 number.toBigInteger().toString()

回答by S.Lott

Use this.

用这个。

BigDecimal truncated= number.setScale(0,BigDecimal.ROUND_DOWN);

回答by ZZ Coder

BigDecimal without fractions is BigInteger. Why don't you just use BigInteger?

没有分数的 BigDecimal 是 BigInteger。为什么不直接使用 BigInteger?

回答by Vinayak Patil

private void showDoubleNo(double n) {
    double num = n; 
    int decimalPlace = 2; 
    BigDecimal bd = new BigDecimal(num); 
    bd = bd.setScale(decimalPlace,BigDecimal.ROUND_UP); 
    System.out.println("Point is "+bd); 
}

回答by Flavio H. Furlanetto

Here's the most elegant way I found to resolve this:

这是我找到的最优雅的解决方法:

public static String convertDecimalToString (BigDecimal num){
    String ret = null;
    try {
        ret = num.toBigIntegerExact().toString();
    } catch (ArithmeticException e){
        num = num.setScale(2,BigDecimal.ROUND_UP); 
        ret = num.toPlainString();
    }
    return ret;
}

回答by puneetShanbhag

public static String convertBigDecimalToString(BigDecimal bg) {
      System.out.println("Big Decimal Value before its convertion :" + bg.setScale(2, BigDecimal.ROUND_HALF_UP));

      String bigDecStringValue = bg.setScale(0,BigDecimal.ROUND_HALF_UP).toPlainString();

      System.out.println("Big Decimal String Value after removing Decimal places is :" + bigDecStringValue);

      return bigDecStringValue;
}

Please note : I have used 'BigDecimal.ROUND_HALF_UP' , just to make sure, Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant

请注意:我使用了 'BigDecimal.ROUND_HALF_UP' ,只是为了确保舍入模式向“最近的邻居”舍入,除非两个邻居等距