Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

I have a BigDecimal number and i consider only 2 decimal places of it so i truncate it using:

bd = bd.setScale(2, BigDecimal.ROUND_DOWN) 

Now I want to print it as String but removing the decimal part if it is 0, for example:

1.00 -> 1

1.50 -> 1.5

1.99 -> 1.99

I tried using a Formatter, formatter.format but i always get the 2 decimal digits.

How can I do this? Maybe working on the string from bd.toPlainString()?

like image 340
res1 Avatar asked Apr 22 '12 15:04

res1


People also ask

How do I remove trailing zeros from BigDecimal?

stripTrailingZeros() is an inbuilt method in Java that returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. So basically the function trims off the trailing zero from the BigDecimal value.

What is the correct way to format the decimal as a String to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do I remove decimal places from String in Java?

String truncated = String. valueOf((int) doubleValue); We can confidently use this approach when we're guaranteed that the double value is within the range of an int.

How do you round BigDecimal to zero decimal places?

You can use setScale() to reduce the number of fractional digits to zero. Assuming value holds the value to be rounded: BigDecimal scaled = value. setScale(0, RoundingMode.


2 Answers

I used DecimalFormat for formatting the BigDecimal instead of formatting the String, seems no problems with it.

The code is something like this:

bd = bd.setScale(2, BigDecimal.ROUND_DOWN);  DecimalFormat df = new DecimalFormat();              df.setMaximumFractionDigits(2);              df.setMinimumFractionDigits(0);              df.setGroupingUsed(false);  String result = df.format(bd); 
like image 146
res1 Avatar answered Sep 19 '22 17:09

res1


new DecimalFormat("#0.##").format(bd) 
like image 39
Federico Cattozzi Avatar answered Sep 21 '22 17:09

Federico Cattozzi