# string to float conversion round off problem

sun ram
Ranch Hand
Posts: 61
Hi,
I am converting a string "149368.87" to a float. The problem is, the fractional part "87" is changed to 88. please refer the code and the output.
How to solve this problem?

Code:
String val = "149368.87";

float f = Float.parseFloat( val);
System.out.println(f);
Ouput:
149368.88

dennis zined
Ranch Hand
Posts: 330
hmmm....works with double though (Double.parseDouble("149368.87"))

Dan Andrei
Ranch Hand
Posts: 92
from SDK documentation:
public static float parseFloat(String s)
throws NumberFormatException
Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class Float.
public static Float valueOf(String s)throws NumberFormatException
Returns a Float object holding the float value represented by the argument string s.
Otherwise, s is regarded as representing an exact decimal value in the usual "computerized scientific notation";
THIS PART IS IMPORTANT:
this exact decimal value is then conceptually converted to an "infinitely precise" binary value that is then rounded to type float by the usual round-to-nearest rule of IEEE 754 floating-point arithmetic, which includes preserving the sign of a zero value. Finally, a Float object representing this float value is returned.

sun ram
Ranch Hand
Posts: 61
I would like to convert as a float value
SR

Dan Andrei
Ranch Hand
Posts: 92
THE WAY I SEE THIS IS THAT THE VALUE IN THE STRING IS IMPLICITLY double
SO FIRST IS CONVERTED FROM DOUBLE TO FLOAT THAT WHY U GET THE DIFF VALUE (roundoff)
TRY APPENDING AN f TO THE END OF THE STRING...

sun ram
Ranch Hand
Posts: 61
its not working
Code
String val = "149368.87f";

float f = Float.parseFloat( val);
System.out.println(f);

output
149368.88
SR

Vicken Karaoghlanian
Ranch Hand
Posts: 522

Dan Andrei
Ranch Hand
Posts: 92
I know I tried it also...
try the code below:
float x=149368.87f;
float yy=x;
System.out.println( yy);
and you'll get the same output
as I said in a previous answer the problem is rounding off of floating point values.

sun ram
Ranch Hand
Posts: 61
Using BigDecimal I was able to print the value, how will I store this in float varible.
Code:
String val = "149368.87";

java.math.BigDecimal b = new java.math.BigDecimal(val);

System.out.println(NumberFormat.getInstance().format(b));
output:
149,368.87
SR