-1

Possible Duplicate:
Strange floating-point behaviour in a Java program
Why does JSP/JSTL division by 1000 sometimes give remainder?

I am trying to get the numbers after the decimal. ex: 60.4 -> 0.4

Yet, when do

double a = 60.4 % 1;

it comes out to be 0.3999999999999986.

Why is this? And how could it be fixed?

Community
  • 1
  • 1
user1364768
  • 2,213
  • 3
  • 16
  • 8
  • 5
    http://floating-point-gui.de/ – PeterMmm May 21 '12 at 09:12
  • 5
    Read and digest : http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html. Floating point primitives have limited precision in Java – mcfinnigan May 21 '12 at 09:12
  • @mcfinnigan or any language - see many duplicates here - but I can't seem to get a good query for tem – mmmmmm May 21 '12 at 09:17
  • 1
    See also the helpful [floating point info. page](http://stackoverflow.com/tags/floating-point/info) *"Many questions asked here about floating point math are about small inaccuracies in floating point arithmetic. To use the example from the excerpt, `0.1 + 0.1 + 0.1` might result in `0.300000001` instead of the expected `0.3`. Errors like these are caused by the way floating point numbers are represented in computers' memory. .."* – Andrew Thompson May 21 '12 at 09:20

3 Answers3

4

Use fixed-point types

BigDecimal src = new BigDecimal("60.4");
BigDecimal a = src.remainder(BigDecimal.ONE);
turbanoff
  • 2,439
  • 6
  • 42
  • 99
1

You can use DecimalFormat to do your desired task.

SilentBomb
  • 168
  • 2
  • 11
0

OK here is how you can do: How to get the numbers after the decimal point? (java)

I think this is exactly what you are looking for. So essentially you can use:

double x = d - Math.floor(d);

OR

BigDecimal class for exact digits after decimal.

Community
  • 1
  • 1
Kuldeep Jain
  • 8,409
  • 8
  • 48
  • 73