I would like to ask how to round numbers as follows:

I am computing a number and i get for example 246,5. I would like to round this number to 250. Another example 581 to 600.

Is there a way to do it in iOS? How?

I actually wanted to round numbers to numbers with multiple of 50). I want to use this to scale the y axis of a graph plot i am generating.

I have an aray of numbers each computed with an equation and i just want to format each one to for exaample of ( 250(if 246,5); (600 if 586,2)

有帮助吗?

解决方案

I don't figure out exactly to what you want to round. In the first example, you round to the next tens. In the second to the next hundreds. Anyway, the general way would be:

import <math.h>
....
NSInteger roundToCloser = 1; // 1 to round to closer unity, 10 closer tens, 100 closer hundreds and so on
CGFloat notRounded = 144.5; // Put yours
NSInteger rounded = roundf(notRounded / roundToCloser) * roundToCloser;
// roundToCloser == 1 -> 144
// roundToCloser == 10 -> 140
// rountToCloser == 100 -> 100
// ....
....

UPDATE: if you want to round by a step of 50, just set roundToCloser to 50:

import <math.h>
....
CGFloat notRounded = 144.5; // Put yours
NSInteger rounded = roundf(notRounded / 50) * 50;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top