【问题标题】:iOS Calculating number don't show decimalsiOS计算数字不显示小数
【发布时间】:2014-01-10 19:19:05
【问题描述】:

当我在应用程序中使用数字进行计算时,我的输出中没有小数! 这是我正在使用的代码:

    int Vijfhonderdmeter = [_VijfHonderd.text intValue];
int vijftienhonderdmeter = [_vijftienhonderd.text intValue];

int vijfdeeldrie = vijftienhonderdmeter / 3;

int puntentotaal = Vijfhonderdmeter + vijfdeeldrie;
_PuntenTotaal.text = [NSString stringWithFormat:@"%d",puntentotaal];

实际输出应该是 87,18667,但我的_Puntentotaal 标签只显示 87。

有人解决了吗?

顺便说一句:

(_VijfHonderd.text intValue = 44.05).
(_vijftienhonderd.text intValue = 129.41).

感谢您的时间和帮助:)

【问题讨论】:

标签: ios objective-c nsstring int decimal


【解决方案1】:

3 个问题:

1) 您正在使用整数除法。如果你想要浮点数,你需要浮点值并进行浮点除法:

double Vijfhonderdmeter = [_VijfHonderd.text doubleValue];
double vijftienhonderdmeter = [_vijftienhonderd.text doubleValue];

double vijfdeeldrie = vijftienhonderdmeter / 3.0;

2) 您正在使用%d 格式化结果。将%fdouble 值一起使用。

3) 使用NSNumberFormatter,而不是stringWithFormat: 来格式化数字。这将确保它们在所有用户的区域设置中看起来都是正确的。

【讨论】:

    【解决方案2】:

    当您使用 int 数据类型进行操作时,您的代码将始终返回一个非十进制值。

    int Vijfhonderdmeter = [_VijfHonderd.text intValue]; here you are getting a non decimal value & later also you are operating it with other non-decimal values. To get decimal values, you should use `double` or `float` datatype.
    

    现在,试试这个:

    float Vijfhonderdmeter = [_VijfHonderd.text floatValue];
    float vijftienhonderdmeter = [_vijftienhonderd.text floatValue];
    
    float vijfdeeldrie = vijftienhonderdmeter / 3;
    
    float puntentotaal = Vijfhonderdmeter + vijfdeeldrie;
    _PuntenTotaal.text = [NSString stringWithFormat:@"%f",puntentotaal];
    

    请参阅 this link 了解有关 Objective-C 中的前导数据类型的更多知识

    【讨论】:

    • 那也行不通。 Int 除以 Int 仍然是 int。将其更改为/ 3.0/3.0f
    • @Putz1103 不,代码是正确的。 float / intfloat 完成。
    • 啊,是的,我的错。我仍在阅读 op 的 int 原语,而不是更新的 float 原语。
    • 我会的,但是您根本没有解释为什么您的代码有效而操作却无效。正确的代码只对此有帮助。了解错误以及错误的原因有助于以后的发展。
    • @Putz1103。好手势。尊重... _/\_ ...编辑了我的答案。看看它,如果还有什么可以添加的,请告诉我
    猜你喜欢
    • 2016-02-16
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    相关资源
    最近更新 更多