98

So I have a double set to equal 1234, I want to move a decimal place over to make it 12.34

So to do this I multiply .1 to 1234 two times, kinda like this

double x = 1234;
for(int i=1;i<=2;i++)
{
  x = x*.1;
}
System.out.println(x);

This will print the result, "12.340000000000002"

Is there a way, without simply formatting it to two decimal places, to have the double store 12.34 correctly?

BlackCow
  • 1,398
  • 2
  • 13
  • 11
  • 30
    Here's a link to the original article ["What Every Computer Scientist Should Know About Floating-Point Arithmetic"](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – bsd Jan 12 '12 at 11:35
  • 44
    Is there a reason you didn't do `x /= 100;` ? – Mark Ingram Jan 12 '12 at 12:23

9 Answers9

190

If you use double or float, you should use rounding or expect to see some rounding errors. If you can't do this, use BigDecimal.

The problem you have is that 0.1 is not an exact representation, and by performing the calculation twice, you are compounding that error.

However, 100 can be represented accurately, so try:

double x = 1234;
x /= 100;
System.out.println(x);

which prints:

12.34

This works because Double.toString(d) performs a small amount of rounding on your behalf, but it is not much. If you are wondering what it might look like without rounding:

System.out.println(new BigDecimal(0.1));
System.out.println(new BigDecimal(x));

prints:

0.100000000000000005551115123125782702118158340454101562
12.339999999999999857891452847979962825775146484375

In short, rounding is unavoidable for sensible answers in floating point whether you are doing this explicitly or not.


Note: x / 100 and x * 0.01 are not exactly the same when it comes to rounding error. This is because the round error for the first expression depends on the values of x, whereas the 0.01 in the second has a fixed round error.

for(int i=0;i<200;i++) {
    double d1 = (double) i / 100;
    double d2 = i * 0.01;
    if (d1 != d2)
        System.out.println(d1 + " != "+d2);
}

prints

0.35 != 0.35000000000000003
0.41 != 0.41000000000000003
0.47 != 0.47000000000000003
0.57 != 0.5700000000000001
0.69 != 0.6900000000000001
0.7 != 0.7000000000000001
0.82 != 0.8200000000000001
0.83 != 0.8300000000000001
0.94 != 0.9400000000000001
0.95 != 0.9500000000000001
1.13 != 1.1300000000000001
1.14 != 1.1400000000000001
1.15 != 1.1500000000000001
1.38 != 1.3800000000000001
1.39 != 1.3900000000000001
1.4 != 1.4000000000000001
1.63 != 1.6300000000000001
1.64 != 1.6400000000000001
1.65 != 1.6500000000000001
1.66 != 1.6600000000000001
1.88 != 1.8800000000000001
1.89 != 1.8900000000000001
1.9 != 1.9000000000000001
1.91 != 1.9100000000000001
Hooray Im Helping
  • 5,004
  • 4
  • 26
  • 42
Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075
  • 26
    I can't believe I didn't think of doing that in the first place! Thanks :-P – BlackCow Feb 08 '11 at 19:55
  • 6
    Although 100 can be represented exactly in binary format, division by 100 cannot be represented exactly. Thus, writing ``1234/100``, as you have done, does not really do anything about the underlying problem -- it should be exactly equal to writing ``1234 * 0.01``. – Brooks Moses Jan 11 '12 at 20:58
  • @BrooksMoses it will if the number is odd. However, if the number is even or a multiple of 5, you will get less rounding error. The extreme example being 100 / 100. In the worst cases examples, `x / 100` and `x * 0.01` should be much the same. – Peter Lawrey Jan 11 '12 at 22:35
  • 1
    @Peter Lawrey: Can you explain more why whether the number is odd or even would affect rounding? I'd think that /=100 and *=.01 would be the same because even though 100 is an int, it will be converted into 100.0 anyways as a result of type coercion. – eremzeit Jan 12 '12 at 07:37
  • 1
    `/100` and `*0.01` are equivalent to each other, but not to OP's `*0.1*0.1`. – Amadan Jan 12 '12 at 07:44
  • @Amadan equivalent perhaps, but not always exactly the same. See my edit. – Peter Lawrey Jan 12 '12 at 08:04
  • @Amadan Double can represent any valid integer between -(1<<53) and (1<<53) (roughly) however, 0.01 is represented with a binary floating point mantissa (64 bit) of [10100011110101110000][10100011110101110000][1010001111011 ]. The brackets are there to mark the repetition. As you can see, the value of 0.01 can NOT be represented perfectly by a float, which is where the inaccuracy comes from. Play around with this to see what's going on http://babbage.cs.qc.edu/IEEE-754/ – Jasper Bekkers Jan 12 '12 at 15:00
  • @Amadan The important thing to remember is that the literal `0.01` is converted into a `Double` before the calculation occurs, introducing the difference. – nemetroid Jan 12 '12 at 17:17
  • 1
    All I'm saying is that multiplying by 0.1 twice will on the average introduce a greater error than multiplying by 0.01 once; but I'll happily concede @JasperBekkers's point about 100 being different, being exactly binary-representable. – Amadan Jan 12 '12 at 18:21
  • @Amadan I agree that 0.1*0.1 != 0.01 in double. – Peter Lawrey Jan 12 '12 at 20:21
  • Are you sure that Double.toString() does rounding? When I do System.out.println((double)0.9999999999999999); System.out.println((double)0.99999999999999999); System.out.println((double)0.9999999999999999==(double)1.0); System.out.println((double)0.99999999999999999==(double)1.0); it prints out the whole of 0.9999999999999999 and prints 0.99999999999999999 as 1.0, and seems to think it is the same as 1.0 as well. Does that mean the rounding is not done in the toString() but already in the internal representation of the number? – user2108462 Jan 10 '15 at 09:40
  • @user2108462 When `0.999..999` becomes `1.0` this is because it is picking the nearest representable value. It is not rounding the sense that while it happens to round this value, a different value might be de-rounded. e.g. `0.1` actually becomes `0.1000000000000000055511151231257827021181583404541015625` as this is the nearest representable value. – Peter Lawrey Jan 10 '15 at 09:50
52

No - if you want to store decimal values accurately, use BigDecimal. double simply can't represent a number like 0.1 exactly, any more than you can write the value of a third exactly with a finite number of decimal digits.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
46

if it's just formatting, try printf

double x = 1234;
for(int i=1;i<=2;i++)
{
  x = x*.1;
}
System.out.printf("%.2f",x);

output

12.34
rrk
  • 14,861
  • 4
  • 25
  • 41
Augusto
  • 26,525
  • 5
  • 52
  • 82
  • 8
    The higher rated answers are more technically insightful, but this is the correct answer to OP's problem. We generally don't care about the *slight* inaccuracy of double, so BigDecimal is overkill, but when displaying we often want to ensure our output matches our intuition, so `System.out.printf()` is the right way to go. – dimo414 Jan 12 '12 at 14:19
30

In financial software it is common to use integers for pennies. In school, we were taught how to use fixed-point instead of floating, but that is usually powers of two. Storing pennies in integers might be called "fixed point" as well.

int i=1234;
printf("%d.%02d\r\n",i/100,i%100);

In class, we were asked in general what numbers can be exactly represented in a base.

For base=p1^n1*p2^n2... you can represent any N where N=n*p1^m1*p2^m2.

Let base=14=2^1*7^1... you can represent 1/7 1/14 1/28 1/49 but not 1/3

I know about financial software -- I converted Ticketmaster's financial reports from VAX asm to PASCAL. They had their own formatln() with codes for pennies. The reason for the conversion was 32 bit integers were no longer enough. +/- 2 billion pennies is $20 million and that overflowed for the World Cup or Olympics, I forgot.

I was sworn to secrecy. Oh well. In academea, if it's good you publish; in industry, you keep it secret.

12

you can try integer number representation

int i =1234;
int q = i /100;
int r = i % 100;

System.out.printf("%d.%02d",q, r);
Angel Koh
  • 10,460
  • 5
  • 53
  • 75
  • 5
    @Dan: Why? This is the correct approach for financial apps (or any other apps where even a tiny rounding error is unacceptable), while still maintaining hardware-level speed. (Of course, it would be wrapped in a class, normally, not written out every time) – Amadan Jan 12 '12 at 07:45
  • 7
    There is a slight problem with this solution - if the remainder `r` is less than 10, no 0 padding occurs and 1204 would produce a result of 12.4. The correct formatting string is more similar to "%d.%02d" – jakebman Apr 16 '12 at 17:05
10

This is caused by the way computers store floating-point numbers. They don't do so exactly. As a programmer, you should read this floating-point guide to familiarize yourself with the trials and tribulations of handling floating-point numbers.

CanSpice
  • 31,336
  • 10
  • 69
  • 86
  • Argh, I was just writing an explanation linking to the exact same place. +1. – Pops Feb 08 '11 at 19:36
  • @Lord Haha, sorry. I got Skeeted anyhow. :-) – CanSpice Feb 08 '11 at 19:37
  • I figured thats why, but I wonder if there is some creative way to move the decimal place over? Because it is possible to store 12.34 cleanly in a double, it just doesn't like the multiplying by .1 – BlackCow Feb 08 '11 at 19:40
  • 1
    If it were possible to store 12.34 cleanly in a double, don't you think Java would have done it? It's not. You'll have to use some other datatype (like BigDecimal). Also, why don't you just divide by 100 instead of doing it in a loop? – CanSpice Feb 08 '11 at 19:46
  • Do'h... yeah, dividing it by 100 results in a clean 12.34... thanks :-P – BlackCow Feb 08 '11 at 19:49
  • Or, more precisely, they are exactly stored as the closest number (1+(n/2**23))*(2*k) where n and k are integers, and 0 <= n < 2**23. There are more details, but none relevant – Aaron Jan 12 '12 at 04:07
9

Funny that numerous posts mention to use BigDecimal but no-one bothers to give the correct answer based on BigDecimal? Because even with BigDecimal, you can still go wrong, as demonstrated by this code

String numstr = "1234";
System.out.println(new BigDecimal(numstr).movePointLeft(2));
System.out.println(new BigDecimal(numstr).multiply(new BigDecimal(0.01)));
System.out.println(new BigDecimal(numstr).multiply(new BigDecimal("0.01")));

Gives this output

12.34
12.34000000000000025687785232264559454051777720451354980468750
12.34

The BigDecimal constructor specifically mentions that it is better to use String constructor than a numeric constructor. Ultimate precision is also influenced by the optional MathContext.

According to the BigDecimal Javadoc it is possible to create a BigDecimal which is exactly equal to 0.1, provided you use the String constructor.

Justin Rowe
  • 2,138
  • 1
  • 18
  • 14
5

Yes, there is. With each double operation you may lose accuracy but the amount of accuracy differs for each operation and can be minimized by choosing the right sequence of operations. For example when multiplying set of numbers, it is best to sort set by exponent before multiplying.

Any decent book on number crunching describes this. For example: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

And to answer your question:

Use divide instead of multiply, this way you get correct result.

double x = 1234;
for(int i=1;i<=2;i++)
{
  x =  x / 10.0;
}
System.out.println(x);
rrk
  • 14,861
  • 4
  • 25
  • 41
Jan Kotek
  • 1,036
  • 7
  • 4
3

No, as Java floating point types (indeed all floating point types) are a trade-off between size and precision. While they're very useful for a lot of tasks, if you need arbitrary precision, you should use BigDecimal.

biziclop
  • 46,403
  • 12
  • 73
  • 97