views:

650

answers:

4

When I give JAVA and C BIG floats and doubles (in the billion range), they convert it to scientific notation, losing precision in the process. How can I stop this behavior?

+11  A: 

For Java, check out BigDecimal

Michael Easter
+7  A: 

The conversion to scientific notation is purely an effect of how it's displayed. Changing the display is a matter of how you output it (format specifiers)

floats generally have about 6 digits of precision, which would make them inappropriate to hold a number in the billions. Doubles have about 15 digits of precision, so it should be able to hold numbers well past trillions with full accuracy.

To display a double in C:

printf("%10f", dbl);
James Curran
A: 

Do you mean that if I convert it to a string, then it will stop this?

chustar
A: 

Thanks. I just did it in JAVA and BigInteger worked! (Using methods to add is a little wierd, though) Thanks for the solution in C. Stack Overflow is awesome!

chustar
You should accept the answer you were happy with. :-)
Andrew
That same C sollution also works in Java:System.out.println( String.format( "%10f", dbl) );BigInteger and BigDecimal are used when accuracy can not be compromised by the inherent rounding of floats and doubles.They are not wrong, but they may be overkill.
extraneon