我是新来的Java,并试图采取一个BigDecimal(例如99999999.99),并将其转换为字符串,但没有小数位和尾号。另外,我不想在数逗号并且不需要舍入。

我已经试过:

Math.Truncate(number)

但不支持的BigDecimal。

任何想法?

非常感谢。

有帮助吗?

解决方案

尝试number.toBigInteger().toString()

其他提示

使用此

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

的BigDecimal无级分是BigInteger的。你为什么不只是使用的BigInteger?

下面是最优雅的方式,我发现解决此问题:

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;
}
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); 
}
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;
}

请注意:我用“BigDecimal.ROUND_HALF_UP”,只是为了确保,舍入模式走向“近邻”,除非两个相邻数字的距离相等

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top