Vins
Vins

Reputation: 1944

Round float at 2 decimal places down to the 0.05 or 0.1

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

Answers (2)

rmaddy
rmaddy

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

Vishnu gondlekar
Vishnu gondlekar

Reputation: 3956

You can try out this

float priceRounded = [[NSString stringWithFormat:@"%.2f",floor(price*20)/20]floatValue]; 

Upvotes: 1

Related Questions