在目标C中格式化浮点数 [英] Formatting floats in Objective C

查看:155
本文介绍了在目标C中格式化浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将float(catchy title,he?)格式化为2个小数位,但前提是这些小数位的值不为零。示例:

I need to format a float (catchy title, he?) to 2 decimal places, but only if those decimal places have values that aren't zero. Example:

我有一个名为answer的NSTextField,在我对一些浮点数做一些数学后,我想将'answerFloat' 'NSTextField。到目前为止我有:

I have a NSTextField named 'answer', after I do some math with a couple of floats, I want to assign my 'answerFloat' variable to the 'answer' NSTextField. So far I've got:

[answer setStringValue:[NSString stringWithFormat:@"%.2f", answerFloat]];

但是它设置为45到45.00。我想要显示没有零的整数,以及要显示的任何十进制数以及它们各自的十进制值。

But that sets something like 45 to 45.00. I want whole numbers to be displayed without the zeroes, and any decimal numbers to be displayed with their respective decimal values.

我需要运行某种检查它到stringWithFormat?或者NSString是否提供了处理这个问题的方法?

Do I need to run some kind of check before giving it to stringWithFormat? Or does NSString offer a way to handle this?

推荐答案

您是否尝试过%g ([NSString stringWithFormat:@%g,%g,45.0,45.5]); c $ c> c $ c>格式说明符

Have you tried the %g format specifier?

NSLog([NSString stringWithFormat:@"%g, %g", 45.0, 45.5]);




2010-01-12 19:54:38.651 foo [89884: 10b]
45,45.5

2010-01-12 19:54:38.651 foo[89884:10b] 45, 45.5

这篇关于在目标C中格式化浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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