Reputation: 303
I have a string: 61146009 [sent from the server]
But when I print its float value
[string floatValue];
The output comes as 61146008.000000. I have tried sending the string as 61146009.0 too, but still the same result.
Any idea why?
The string needs to be displayed as 61,146,009 by using
NSString *formattedScore = [numberFormatter stringFromNumber: [NSNumber numberWithFloat: [scoreString floatValue]]];
It was a line of code written by somebody else who seems to have used float by mistake instead of int
I know using [string intValue] will fix it easily. But unfortunately the code is live with [string floatValue] and I am trying to fix the issue without having to release a new update.
Any help is appreciated. Thanks.
Upvotes: 0
Views: 317
Reputation: 223843
If the server sends the string “61146009”, then one of these is true:
The reason I list 2 is that 61146009 is not representable as an IEEE 754 single-precision value. As you have seen, the nearest representable value is 61146008. If the server has 61146008 and conversion to a string produced 61146009, then its formatting routine is bad and should be fixed or replaced. Your fix would be to change how the server converts the number to a string.
In the case of 1, the server has numbers that cannot be represented in a float (IEEE 754 single-precision object). This makes it impossible for the client to store them in a float. Since you do not want to change the client, you would have to change the server never to send values that cannot be represented in float. One way to do this is to modify the server to convert its value to single precision, then send it. The conversion will round the double-precision value to something representable in single precision.
The case of 3 is similar to 1: The server has numbers that cannot be represented in a float, and you would need to convert similarly.
Given what you have described, I do not expect there is any value you could send that would cause an unmodified client to display 61146009.
Upvotes: 3
Reputation: 5316
Use a double, not a float. Float has approximately 7 decimal digits of precison.
Upvotes: 3
Reputation: 9572
This number is not representable in single precision float.
In hexa decimal, it is 0x3A50399, it thus needs 26 bits, two more bits than the 24 available in a Float mantissa.
So, you get the nearest Float number to your decimal input.
Upvotes: 2
Reputation: 1116
Have you tried:
[NSString stringWithFormat:@"%.0f",string]
Upvotes: 0