Bug 306 : toFloat() of Strings has floating point errors
Last modified: 2006-03-16 08:28




Status:
RESOLVED
Resolution:
INVALID -
Priority:
P2
Severity:
normal

 

Reporter:
jason
Assigned To:
fry

Attachment Type Created Size Actions

Description:   Opened: 2006-03-16 08:13
Don't know if this is a problem with Java itself, or related to Bug #4, but
when trying to parse a large number (e.g., the 6 billion + world
population) from string to float, the 100-million digit converts
improperly, skewing the conversion.

void setup(){
String World_Population = "6,403,622,583";

//take out the commas for conversion to float
String World_Population2 = "";
char letter = ',';
for(int i=0;i<World_Population.length(); i++){
letter = World_Population.charAt(i);
if (letter != ',') World_Population2+= letter;
}

// print string number
println(World_Population2 + " is "+World_Population2.length()+"
characters long");
float World_Pop = toFloat(World_Population2);
// print converted number with commas
println(nfc(World_Pop, 0));
// ...print without
println(World_Pop);
// separate out each digit and convert it individually
println(nfc(makeNumber(World_Population2),0));
}

float makeNumber(String strnum) {
float finalnum = 0.0;
String singchar = "";
for(int i=0;i<strnum.length(); i++){
singchar += strnum.charAt(i);
print(toFloat(singchar));
print(" x 10 ^ "+abs(i-strnum.length()+1));
print(" = "+toFloat(singchar)*pow(10,abs(i-strnum.length()+1)));
if(abs(i+1-strnum.length())>2) finalnum +=
toFloat(singchar)*pow(10,abs(i-strnum.length()+1));
println( " :: total :: " + finalnum + " :: "+nfc(finalnum,0));
singchar="";
}
return finalnum;
}
Additional Comment #1 From fry 2006-03-16 08:16
you should use an int, not a float, to store that sort of number. floats aren't made to be
accurate at that range (they're 32 bits, and the accuracy varies across the range of values it
can represent). since it not as though you're going to have a fractional number of people, you
should most certainly use an int.
Additional Comment #2 From jason 2006-03-16 08:24
> you should use an int, not a float, to store that sort of number.

Thank you.
What if there are cases, however, when you want to work with a number that
is much larger than the maximum int value? (If you switch all of the
floats to ints in the code above, it caps at 2,147,483,647.) I take it
this is just not doable...and one should use kludgey workarounds?
Additional Comment #3 From fry 2006-03-16 08:28
if you need bigger numbers, you use a long instead of an int. if you need bigger floats you use
a double. but this sort of question should go on the discourse board, not the bugs db ;)