Reputation: 1944
I have a float and want to round like this:
1.31 = 1.30
1.34 = 1.30
1.37 = 1.35
1.39 = 1.35
my (wrong)code:
float price = 1.3791;
float priceRounded = [[NSString stringWithFormat:@"%.2f",price]floatValue];
Upvotes: 0
Views: 186
Reputation: 318955
You can eliminate the use of stringWithFormat:
by doing:
float princeRounded = (long)(price * 20) / 20.0;
This multiples price
by 20 then takes the integer result of that (round down basically), and then divides that result by 20 ensuring that the result always ends in .05
, .1
, .15
, etc.
Please note that this always rounds down to the 0.05 or 0.1 like you show in your examples. This isn't the same is rounding to the nearest 0.05 or 0.1 as in your title.
Upvotes: 2
Reputation: 3956
You can try out this
float priceRounded = [[NSString stringWithFormat:@"%.2f",floor(price*20)/20]floatValue];
Upvotes: 1