目标c中有一个数字的浮点数是否有简单的方法? [英] Is there any easy way to round a float with one digit number in objective c?
问题描述
是。你是对的。当然这是一个重复的问题。在标记我的问题之前,请继续阅读下面的内容。
我想将一个float值,即
56.6748939至56.7
56.45678至56.5
56.234589至56.2
实际上它可以是任意数量的小数精度。但我想把它凑到最近的价值。 (如果它大于或等于5,则循环,如果不是,则循环下去)。
我可以用下面的代码。
$ b $ pre $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
[numberFormatter setMaximumFractionDigits:1];
[numberFormatter setRoundingMode:NSNumberFormatterRoundUp];
NSString * roundedString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:value]];
NSNumber * roundedNumber = [NSNumber numberFromString:roundedString];
float roundedValue = [roundedNumber floatValue];
上面的代码看起来像一个漫长的过程。我有几个数字四舍五入。 所以这个过程很难将浮点值转换成NSNumber和NSString,并转换成NSNumber并浮动。
有没有其他简单的方法实现我所问的?
我仍然怀疑上面的代码。它说 roundUp
。所以当谈到 roundDown
时,它会起作用吗?
你只需乘以10,然后除以10?
Yes. You are right. Of Course this is a duplicate question. Before flag my question, please continue reading below.
I want to round a float value, which is
56.6748939 to 56.7
56.45678 to 56.5
56.234589 to 56.2
Actually it can be any number of decimal precisions. But I want to round it to nearest value. (If it is greater than or equal to 5, then round up and if not, then round down).
I can do that with the below code.
float value = 56.68899
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
[numberFormatter setMaximumFractionDigits:1];
[numberFormatter setRoundingMode:NSNumberFormatterRoundUp];
NSString *roundedString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:value]];
NSNumber *roundedNumber = [NSNumber numberFromString:roundedString];
float roundedValue = [roundedNumber floatValue];
Above code looks like a long process. I have several numbers to round off. So this process is hard to convert a float value into NSNumber and to NSString and to NSNumber and to float.
Is there any other easy way to achieve what I asked ?
I still have a doubt in the above code. It says roundUp
. So when it comes to roundDown
, will it work?
Can't you simply multiply by 10, round the number, then divide by 10?
这篇关于目标c中有一个数字的浮点数是否有简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!