# working with decimal point numbers

• December 8th, 2013, 11:47 PM
raam
working with decimal point numbers
Good Morning,
please suggest me a better code .

// my java program goes like this

public class FloatingNumber {

public static void main(String...args) {

double i;
double num=0.0;
for(i=0.0;i<10;i++)
num=num+0.1;

System.out.println(num);

}

}

// output: 0.9999999999999999

// The same program in C goes like this

#include<stdio.h>
#include<math.h>

main()

{
double i, num=0.0;

for(i=0;i<10;i++)
num=num+0.1;
printf("%f",num);

}

// output=1.0000

/** please do explain me why java is not producing an accurate value as C program did.
For an accurate result , please do sugges me good code for java
• December 9th, 2013, 01:50 AM
CruelCoin
Re: working with decimal point numbers
You can use math.round to round to 1.0
• December 9th, 2013, 02:02 AM
andbin
Re: working with decimal point numbers
Quote:

Originally Posted by raam
/** please do explain me why java is not producing an accurate value as C program did.

Floating-point numbers have these problems because they are stored on a finite number of bits. This happens in Java, in C, in C#, in Javascript, etc...
Floating-point numbers cannot accurately represent all numbers. For example 0.3 cannot be accurately represented. It will be very very close to 0.3 but never exactly 0.3. Where you can "see" a difference is when there is an implicit or explicit rounding, especially when you use some "print" method.
You should understand this before criticizing your or other code. ;)
• December 9th, 2013, 06:29 AM
PhHein
Re: working with decimal point numbers