Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS round a float

Tags:

I have a floating point number that have more decimal digits, for example:

float fRes = 10.0 / 3.0; 

actually the fRes value is 3.3333333333333 it's possible set for example 2 decimal digits:

float fRes = 10.0 / 3.0; // fRes is 3.333333333333333333333333 float fResOk = FuncRound( fRes, 2 ); // fResOk is 3.33 

thanks in advance

like image 917
ghiboz Avatar asked Jul 13 '11 11:07

ghiboz


People also ask

Can you round a float?

Use round() to round a float in Python Call the built-in function round(number, digits) on a float with the number of digits after the decimal point to round to digits to get float rounded to digits digits after the decimal point.

How do you round up a float?

Option 1: Python Round Function Python has an inbuilt function round(), which will take the float value and round it off. The round() function takes two parameters: Number and Ndigits (optional). Ndigits represent the number of decimal places to round.

How do you round a float in Swift?

By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.

How do you round a float to 2 digits?

To round up a float to 2 decimals:ceil() method, passing it the number multiplied by 100 . Divide the result by 100 . The result of the calculation will be the float number rounded up to 2 decimals.


2 Answers

I don't know where you are using this rounded number, but you should only round your value when displaying it to the user, there are C based format string ways to round floating point numbers for example

[NSString stringWithFormat:@"%.2f", value]; 

as you may have already read, floating point number are approximations of real numbers, so doing fResOk = roundf( fRes*100.0)/100.0; may not give you 3.33 but a number which is just as close as you can get with floating point number to 3.33.

like image 107
Nathan Day Avatar answered Sep 22 '22 10:09

Nathan Day


Assuming that you're looking for the correct function to round to a certain number of digits, you'll probably find it easiest to do the following:

fResOk = roundf( fRes*100.0)/100.0; 

That will multiply the value by 100 (giving you your 2 digits of significance), round the value, and then reduce it back to the magnitude you originally started with.

like image 20
gaige Avatar answered Sep 19 '22 10:09

gaige