从字符串到浮点数的转换更改了数字 [英] Conversion from string to float changes the number

查看:169
本文介绍了从字符串到浮点数的转换更改了数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:61146009 [从服务器发送]

但是,当我打印它的浮点值

  [string floatValue]; 

输出为61146008.000000。我曾尝试发送字符串为61146009.0太,但仍然是相同的结果。



任何想法为什么?

该字符串需要显示为61,146,009通过使用

  NSString * formattedScore = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:[scoreString floatValue] ]]; 

这是由其他人编写的一行代码,似乎错误地使用了float而不是int

我知道使用[string intValue]会很容易修复。但不幸的是代码是与[字符串floatValue]生活,我试图解决这个问题,而不必发布一个新的更新。

任何帮助表示赞赏。谢谢。

解决方案

使用double而不是float。浮点数大约有7位精度。


I have a string: 61146009 [sent from the server]

But when I print its float value

[string floatValue];

The output comes as 61146008.000000. I have tried sending the string as 61146009.0 too, but still the same result.

Any idea why?

The string needs to be displayed as 61,146,009 by using

NSString *formattedScore = [numberFormatter stringFromNumber: [NSNumber numberWithFloat: [scoreString floatValue]]];

It was a line of code written by somebody else who seems to have used float by mistake instead of int

I know using [string intValue] will fix it easily. But unfortunately the code is live with [string floatValue] and I am trying to fix the issue without having to release a new update.

Any help is appreciated. Thanks.

解决方案

Use a double, not a float. Float has approximately 7 decimal digits of precison.

这篇关于从字符串到浮点数的转换更改了数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆