如何获取带小数的格式数字(XCode) [英] How to get format numbers with decimals (XCode)

查看:64
本文介绍了如何获取带小数的格式数字(XCode)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是为iPhone创建一个客户计算器应用程序,而我正在使用Xcode编写我的应用程序。我的问题(我找不到解决方案)是如何格式化不使用科学计数法的使用小数(带有额外的零)的数字

My objective is to create a customer calculator application for iPhone and I am using Xcode to write my application. My problem, that I cannot find a solution for, is how to format a number that uses decimals (with extra zeros) without switching into scientific notation

我尝试过...

buttonScreen.text = [NSString stringWithFormat:@"%0.f",currentNumber];

%0.f 格式总是四舍五入如果用户键入 4.23,则显示 4

%0.f formatting always rounds so if the user types in "4.23" it displays "4"

%f 格式化带有6位小数的数字(键入在 5中显示为 5.000000),但我不想在数字的末尾显示额外的零。

%f formats numbers with 6 decimals (typing in '5' displays as '5.000000'), but I don't want to show extra zeros on the end of the number.

% 10.4f 是我在阅读中发现的另一种方法,但是我的问题是我不知道答案中会有多少个小数,因此我可能想要零个小数或10位小数,取决于数字。

%10.4f is something else that I have seen in my reading to find the solution, but my problem is that I don't know how many decimals will be in the answer, and I may want zero decimals or 10 decimals depending on the number.

以下是我要显示的数字示例(不带逗号):大于6位数字的整数,十进制

The following are examples of numbers I'd like to display (without the commas): A whole number larger than 6 digits, a decimal number with more than 6 digits.

123,456,789;
0.123456789;
12345.6789;
-123,456,789;
-0.23456789;
-12345.6789;

*这是我先前的问题如何在不使用科学计数法或小数点的情况下格式化数字的精神转贴在我打算写不必要的(多余的零)时,我措辞很差,但是在重读我的帖子后,我清楚地看到了我无法在问题的任何地方传达这一点。

*This is a spiritual repost to my earlier question "How to Format Numbers without scientific notation or decimals" which I poorly phrased as I intended to write 'unnecessary (extra zeros),' but upon rereading my post clearly witnessed my inability to convey that at any point in my question.

推荐答案

使用 NSNumberFormatter类

首先定义格式化程序:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

然后,您可以定义格式化程序的各种属性:

Then you can define various properties of the formatter:

formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.maximumIntigerDigits = 3;
formatter.minimumFractionDigits = 3;
formatter.maximumFractionDigits = 8;
formatter.usesSignificantDigits = NO;
formatter.usesGroupingSeparator = YES;
formatter.groupingSeparator = @",";
formatter.decimalSeparator = @".";
....

您可以将数字格式化为这样的字符串:

You format the number into a string like this:

NSString *formattedNumber = [formatter stringFromNumber:num];

试一下。它非常简单,但可能需要一些工作才能获得所需的外观。

Play around with it. Its pretty simple, but may take some work to get the look you would like.

这篇关于如何获取带小数的格式数字(XCode)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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