iPhone:如何截断浮点数而不进行四舍五入?
我需要简单地截断浮点数(截断而不是四舍五入)。
float FloatNum = 43.6823921;
NSString *numString = [NSString stringWithFormat:@"%.1f", FloatNum]; // yields 43.7
I need to simply truncate a floating point number (truncate and not round it).
float FloatNum = 43.6823921;
NSString *numString = [NSString stringWithFormat:@"%.1f", FloatNum]; // yields 43.7
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以采取多种方法,但您的解决方案将取决于许多因素。
这总是会截断到十分位。
正如 chown 提到的,您可以将其转换为字符串并获取子字符串。如果您不总是处理两位数数字,您可能需要使用
rangeOfString:
os 来查找小数点。另一种选择是使用
NSDecimalNumber
及其方法decimalNumberByRoundingAccordingToBehavior:
来显式设置舍入。我曾多次使用此选项来处理货币操纵,其中准确性非常重要。There are many ways you can do, but your solution is going to depends on a number of factors.
This will always truncate to the tenths place.
As chown mentioned, you can convert it to a string and take the substring. You might want to use
rangeOfString:
os something to find the decimal if you don't always deal with double digit numbers.Another option would be to use
NSDecimalNumber
with it's methoddecimalNumberByRoundingAccordingToBehavior:
to set rounding explicitly. I've used this option a few times to handle currency manipulations where accuracy is very important.这会将浮点数转换为字符串,获取索引 4 的子字符串,然后转换回浮点数。我认为这是截断浮点而不进行舍入的常用方法:float myTruncatedFloat = [[[[NSNumber numberWithFloat:43.6823921] stringValue] substringToIndex:4] floatValue]; 。这会将
43.6823921
转换为43.68
。印刷:
This will convert a float to string, get the substring to index 4, the convert back to a float. I think this is the usual way of truncating a float without rounding at all:
float myTruncatedFloat = [[[[NSNumber numberWithFloat:43.6823921] stringValue] substringToIndex:4] floatValue];
. This will convert43.6823921
into43.68
.Prints: