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
SCSecA,SCNA,SCSA,SCWCD,SCJP
dennis zined
Ranch Hand
Joined: Mar 07, 2003
Posts: 330
posted
0
hmmm....works with double though (Double.parseDouble("149368.87"))
SCJP 1.4<br />SCWCD 1.4
Dan Andrei
Ranch Hand
Joined: Jan 21, 2004
Posts: 92
posted
0
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.
"Did anyone understand what I have just explained? ... because I did not!"
sun ram
Ranch Hand
Joined: Dec 18, 2001
Posts: 61
posted
0
I would like to convert as a float value SR
Dan Andrei
Ranch Hand
Joined: Jan 21, 2004
Posts: 92
posted
0
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
Joined: Dec 18, 2001
Posts: 61
posted
0
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
Joined: Jul 21, 2003
Posts: 522
posted
0
Check out this article by Thomas Paul. I think it'll help.
- Do not try and bend the spoon. That's impossible. Instead, only try to realize the truth. <br />- What truth? <br />- That there is no spoon!!!
Dan Andrei
Ranch Hand
Joined: Jan 21, 2004
Posts: 92
posted
0
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
Joined: Dec 18, 2001
Posts: 61
posted
0
Using BigDecimal I was able to print the value, how will I store this in float varible. Code: String val = "149368.87";