ios – 如何在给定整数时不显示不必要的零,但在需要时仍然有浮动答案

我有一个我正在开发的应用程序,我的一个功能是在需要时给出float或double值的答案,当答案是整数时给出一个整数

所以例如如果答案是8.52,则答案变为8.52,但当答案为8时答案是8而不是8.0000,我不希望它显示所有额外的0.

- (IBAction) equalsbutton {
Nsstring *val = display.text;
switch(operation) {

    case Plus :
        display.text= [Nsstring stringWithFormat:@"%qi",[val longLongValue]+[storage longLongValue]];

    case Plus2 :
        display.text= [Nsstring stringWithFormat:@"%f",[val doubleValue]+[storage doubleValue]];

这段代码似乎不起作用

解决方法

这些说明符是 standard IEEE format specifiers,这意味着您可以执行%.2f之类的操作,只在float变量上显示2个小数位.

您也可以将其转换为int,然后使用%d格式说明符,如果您想这样做的话.

关于这个问题,这里也是Apple’s documentation.

编辑:根据你对另一篇文章评论,看起来你正在寻找%g,这将基本上从浮动中删除无关的0.

display.text= [Nsstring stringWithFormat:@"%g",[val doubleValue]+[storage doubleValue]];

在这里找到了答案:Use printf to format floats without decimal places if only trailing 0s

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...