I have a program like this ,
BigDecimal bd = new BigDecimal(23.086);
BigDecimal bd1= new BigDecimal(0.000);
bd = bd.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros();
bd1 = bd1.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros();
System.out.println("bd value::"+ bd);
System.out.println("bd1 value::"+ bd1);
I get the following output: 23.09
for bd
and 0.00 for bd1
, but I want bd1
as 0
not as 0.00
. Am I applying the methods correctly?
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.
try this
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class calculator{
public static void main(String[] args) {
BigDecimal bd = new BigDecimal(23.086);
BigDecimal bd1= new BigDecimal(0.000);
DecimalFormat df = new DecimalFormat("0.##");
System.out.println("bd value::"+ df.format(bd));
System.out.println("bd1 value::"+ df.format(bd1));
}
}
Let's say you have BigDecimal with value 23000.00
and you want it to be 23000
. You can use method stripTrailingZeros()
, but it will give you "wrong" result:
BigDecimal bd = new BigDecimal("23000.00");
bd.stripTrailingZeros() // Result is 2.3E+4
You can fix it by calling .toPlainString()
and passing this to the BigDecimal constructor to let it handle correctly:
BigDecimal bd = new BigDecimal("23000.00");
new BigDecimal(bd.stripTrailingZeros().toPlainString()) // Result is 23000
Simple, clean, flexible, easy-2-understand and maintain code
(will work for double
too)
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2); //Sets the maximum number of digits after the decimal point
df.setMinimumFractionDigits(0); //Sets the minimum number of digits after the decimal point
df.setGroupingUsed(false); //If false thousands separator such ad 1,000 wont work so it will display 1000
String result = df.format(bd);
System.out.println(result);
BigDecimal bd = new BigDecimal(23.086);
BigDecimal bd1 = new BigDecimal(0.000);
bd = bd.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros();
bd1 = bd1.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros();
System.out.println("bd value::"+ bd); System.out.println("bd1 value::"+ bd1);
System.out.println("new way:" + bd1.intValueExact());
//OUTPUT bd value::23.09
bd1 value::0.00
new way:0
You can use printf()
-- the %f
specifier works for BigDecimal
s too:
System.out.printf("bd1 value::%.0f%n", bd1);
bd1 value::0
You can do this
System.out.println("bd value: " + ((bd.scale() == 0) ? bd.unscaledValue() : bd));
This method below works better IMO
bd1 = bd1.stripTrailingZeros();
System.out.println(bd1.toPlainString());
Prints:
0
If bd1 = 1.2300 , this will print
1.23
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With