Java BigDecimal errors with String constructor for rounding with ROUND_HALF_UP

I am trying to implement a new rounding class for the BigDecimal class and I am getting a possible error, maybe I am doing something wrong. The code below presents my problem:

public static void main(String[] args) throws IOException { BigDecimal valDouble = new BigDecimal(0.35); valDouble = valDouble.setScale(1, BigDecimal.ROUND_HALF_UP); System.out.println(valDouble.doubleValue()); // prints 0.3 BigDecimal valString = new BigDecimal(new String("0.35")); valString = valString.setScale(1, BigDecimal.ROUND_HALF_UP); System.out.println(valString.doubleValue()); // prints 0.4 } 

My doubt is that BigDecimal is different for double and String constructors?

I cannot understand this β€œerror”, at least I just used a simple concat line to β€œsolve” it, as shown below:

 BigDecimal valDouble = new BigDecimal("" + 0.35); 

Any idea what might cause this weird behavior?

+4
java rounding bigdecimal
Jul 6 2018-12-12T00:
source share
3 answers

It's not a mistake. 0.35 as a double literal represents a value that is not exactly equal to 0.35; this is probably something like 0.349999995 or something like that. Thus, it is rounded.

The String constructor allows you to specify 0.35 using "0.35", and is rounded.

Do not use the double constructor here; when it matters to use BigDecimal , you need to stay away from floating-point land.

+7
Jul 06 2018-12-12T00:
source share

You do not need to guess what 0.35 means as

 BigDecimal valDouble = new BigDecimal(0.35); System.out.println(valDouble); 

prints

 0.34999999999999997779553950749686919152736663818359375 

This will be rounded to 1 decimal place of 0.3

You do not need to convert to String, you can use valueOf

 BigDecimal valDouble = BigDecimal.valueOf(0.35); System.out.println(valDouble); 

prints

 0.35 

To round half to one decimal place, you can use

 double d = 0.35; double d1 = Math.round(d * 10) / 10.0; System.out.println(d1); 

prints

 0.4 
+3
Jul 06 2018-12-12T00:
source share

0.35 is already inaccurate, became the binary base of FP. Use the new BigDecimal ("0.35"), which is accurate, because of the decimal base.

0
Jul 07 2018-12-12T00:
source share



All Articles