?

Hi, please explain to me why the following happens:

publicclass test

{

publicstaticvoid main(String[] args)

{

System.out.println("9.54*10 = "+(9.54*10) );

}

}

outputs: 9.54*10 = 95.39999999999999

and not: 9.54*10 = 95.4

I齧 using:

java version "1.4.1_01"

Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1_01-b01)

Java HotSpot(TM) Client VM (build 1.4.1_01-b01, mixed mode)

on Microsoft Windows 2000 [Version 5.00.2195]

thank you,

ss

[845 byte] By [iss3a] at [2007-9-28 6:47:18]
# 1

This will give you 95.4:

System.out.println( "9.54*10 = "+(9.54f*10) );

The float value 9.54f is not the same as the double value 9.54d and neither is the exact value of 9.54. When you're dealing with floating point arithmetic you need to remember that floating point values aren't exact.

luke_hillarya at 2007-7-9 17:58:36 > top of Java-index,Archived Forums,Java Programming...
# 2

It's rounding error caused by the distinction between decimal and binary number formats.

A number may look simple in decimal but may not be easily represented in binary using a restricted number of 0s or 1s. Thus your decimal number is only approximately represented in binary unless you use one of Java's "exact" number objects.

You've got various options:

1) use something like BigDecimal to represent your decimal "exactly"

2) simply account for rounding error in your program by printing it out to N decimal places using a DecimalFormat

Hope this helps.

KPSeala at 2007-7-9 17:58:37 > top of Java-index,Archived Forums,Java Programming...
# 3

The reason they are not exact is due to the way in which floating point values are represented in binary. To get a better understanding of this try these sites:

http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html

http://www.math.grin.edu/~stone/courses/fundamentals/IEEE-reals.html

AJMeyera at 2007-7-9 17:58:37 > top of Java-index,Archived Forums,Java Programming...
# 4

> Hi, please explain to me why the following happens:

>

> > public class test

> {

> public static void main(String[] args)

> {

> System.out.println( "9.54*10 = "+(9.54*10) );

> }

> }

>

>

> outputs: 9.54*10 = 95.39999999999999

> and not: 9.54*10 = 95.4

>

>

> I齧 using:

> java version "1.4.1_01"

> Java(TM) 2 Runtime Environment, Standard Edition

> (build 1.4.1_01-b01)

> Java HotSpot(TM) Client VM (build 1.4.1_01-b01, mixed

> mode)

> on Microsoft Windows 2000 [Version 5.00.2195]

>

> thank you,

> ss

95.39999999999999 is the exact number Java has for this value.

if you want 95.4 you must use:

public static void main(String[] args)

{

double n=(9.54*10);

NumberFormat numb = NumberFormat.getInstance();

numb.setMaximumFractionDigits(1);

System.out.println( "9.54*10 = "+numb.format(n));

}

*** import java.txt.NumberFormat;

benc3a at 2007-7-9 17:58:37 > top of Java-index,Archived Forums,Java Programming...