Knodel
Knodel

Reputation: 4389

Determine where is the first zero in a float number

In my app I have a few random float numbers. I have to determine, where does the period of zero's start to cut the number and display it in an UILabel.

So, for example, if I have number 3.05 it is displayed as 3.0500000 while I want it to be displayed properly '3.05'.

Upvotes: 0

Views: 280

Answers (4)

deanWombourne
deanWombourne

Reputation: 38475

Use the format specifiers :

// Print max two numbers after the decimal point
NSString *string = [NSString stringWithFormat:@"%.2f", number];

If you need to work out the position of the first 0, render it to a string and then search that string for the first '0'

// Render the complete string
NSString *completeNumber = [NSString stringWithFormat:@"%f", number];

// Get the first 0
NSRange range = [completeNumber rangeOfString:@"0"];

// Trim the string
NSString myString = [completeNumber substringWithRange:NSMakeRange(0, range.location)];

Upvotes: 2

Chuck
Chuck

Reputation: 237070

There's a problem with your question: There aren't repeating zeroes in that float. More specifically, the floating-point representation of 3.05 is not actually equal to 3.05 — it's actually more like 3.04999999999999982236431605997495353221893310546875. Your best bet if this is important would be to use something like NSDecimalNumber and its string conversion methods. It can precisely represent base-10 numbers, unlike binary floating-point.

Upvotes: 0

Max
Max

Reputation: 16719

The easiest way is to use length limitation like @"%.2f". But i think if you want to rim zeroes you should use this:

NSString* string = [[NSString stringWithFormat: @"%f", 3.05000000] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: @"0"]];

Will return 3.05

NSString* string = [[NSString stringWithFormat: @"%f", 3.0500100000] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: @"0"]];

Will return 3.05001 while @"%.2f" will return 3.05

You should notice the rounding errors, so for number 3.0500000010000 the string 3.05 would be returned.

Upvotes: 3

hanumanDev
hanumanDev

Reputation: 6614

have you tried:

NSString* myNumber = [NSString stringWithFormat:@"%.02f", number];

with 2 digits:

@"%.02f" = 3.05

with 3 digit:

@"%.03f" = 3.050

Upvotes: 0

Related Questions