# data of more than 7 digits is rounded up by 1

• 05-10-2011, 10:38 AM
data of more than 7 digits is rounded up by 1
Hi,
I have a small doubt , when using 'Float', data of more than 7 digits is rounded up by 1.
piece of code is given below:
<code>

String _val = "51300123";
Float f = new Float (_val);
System.out.println(f);

</code>

I am getting output as 5.1300124E7 .
But when i tried with 7 digits ie; when put _val = "5130012"; getting o/p as 5130012.0
This problem occurs only when there are more than 7 digits.
Can anyone help me in resolving this. I need to get the exact Output without rounding..
It is Urgent

Thanks,
• 05-10-2011, 10:46 AM
sunde887
Don't include urgent in your posts. Floating point is not exact and will always cause problems.

Run this to see how it looks
Code:

```for(float f = 0; f < 1; f+=.1){   System.out.println(f); }```
• 05-10-2011, 10:55 AM
JosAH
Quote:

Hi,
I have a small doubt , when using 'Float', data of more than 7 digits is rounded up by 1.
piece of code is given below:
<code>

String _val = "51300123";
Float f = new Float (_val);
System.out.println(f);

</code>

I am getting output as 5.1300124E7 .
But when i tried with 7 digits ie; when put _val = "5130012"; getting o/p as 5130012.0
This problem occurs only when there are more than 7 digits.
Can anyone help me in resolving this. I need to get the exact Output without rounding..
It is Urgent

Oh dear, I hope I'm not too late ... read the Fload class API documentation: a float uses 23 bits for its mantissa; this means that it can represent the numbers in the range [0, 2^23) exactly (shifted right or left optionally);2^23 is a bit larger than 8 million, that explains it.

kind regards,

Jos
• 05-10-2011, 10:55 AM
pbrockway2
Quote:

I need to get the exact Output without rounding.

System.out.println(_val); won't do any rounding...

More seriously, Oracle's Tutorial on the Types, Values and Variables page reccommends not using float for precise values. It gives links explaining how to use BigDecimal and how to format numeric values.
• 05-10-2011, 12:31 PM
DarrylBurke