2

i would like to know how to get the fractional part of a double. Im trying the following code:

double auxValMin= Double.parseDouble("5.3");
double auxDecimal= auxValMin-floor(auxValMin);
System.out.println(auxDecimal); //I get 0.2999999999999998 instead of 0.3

How can i fix the "0.2999999999999998"?

user207421
  • 305,947
  • 44
  • 307
  • 483
BoxEdition
  • 47
  • 5

2 Answers2

1

double has more accuracy of precision that float but still has rounding errors. You have to round any answer you get to have a sane output.

If this is not desireable you can use BigDecimal which does not have rounding errors, but has its own headaches IMHO.

The default Float.toString() uses minimal rounding, but often its not enough.

System.out.println("With no rounding");
double n = 5.3d;
System.out.println("n= "+new BigDecimal(n));
double expected = 0.3d;
System.out.println("expected= "+new BigDecimal(expected));

System.out.println("n % 1= "+new BigDecimal(n % 1));
System.out.println("n - Math.floor(n) = "+new BigDecimal(n - Math.floor(n)));
System.out.println("n - (int)n= "+new BigDecimal(n - (int)n));

System.out.println("With rounding");
System.out.printf("n %% 1= %.2f%n", n % 1);
System.out.printf("n - Math.floor(n) = %.2f%n", n - Math.floor(n));
System.out.printf("n - (int)n= %.2f%n", n - (int)n);

Prints

With no rounding
n= 5.29999999999999982236431605997495353221893310546875
expected= 0.299999999999999988897769753748434595763683319091796875
n % 1= 0.29999999999999982236431605997495353221893310546875
n - Math.floor(n) = 0.29999999999999982236431605997495353221893310546875
n - (int)n= 0.29999999999999982236431605997495353221893310546875 
With rounding
n % 1= 0.30
n - Math.floor(n) = 0.30
n - (int)n= 0.30

A bit of a googling might have helped : https://stackoverflow.com/a/5017110/820410

Community
  • 1
  • 1
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86
1

Now a day BigDecimal you will get Java.Please read and learn it about BigDecimal

 BigDecimal value=new BigDecimal("5.36777777");
    System.out.println( value.round(new MathContext(2, RoundingMode.CEILING)));
Abhishek Mishra
  • 611
  • 4
  • 11