2009-08-22 36 views
15

我是新来的Java和尝试采取BigDecimal(例如99999999.99)并将其转换为字符串,但没有小数位和尾随数字。另外,我不想在逗号中输入逗号,舍入也不需要。Java BigDecimal删除十进制和结尾数字

我已经试过:

Math.Truncate(number) 

但不支持BigDecimal的。

任何想法?

非常感谢。

回答

31

尝试number.toBigInteger().toString()

+0

完美,谢谢。 – 2009-08-22 23:26:22

34

使用此项。

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

BigDecimal without fractions是BigInteger。你为什么不使用BigInteger?

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

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

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; 
} 
0
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”,只是为了确保,舍入模式走向“最近的邻居”除非两个邻居都是等距的

相关问题