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.
I've tried:
Math.Truncate(number)
but BigDecimal is not supported.
Any ideas?
Thanks very much.
Try number.toBigInteger().toString()
Use this.
BigDecimal truncated= number.setScale(0,BigDecimal.ROUND_DOWN);
BigDecimal without fractions is BigInteger. Why don't you just use BigInteger?
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;
}
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);
}
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
来源:https://stackoverflow.com/questions/1316945/java-bigdecimal-remove-decimal-and-trailing-numbers