How to get format numbers with decimals (XCode)

亡梦爱人 提交于 2019-11-30 16:30:09

Use the NSNumberFormatter class.

First define the formatter:

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.

Actually, it makes more sense to use this:

label.text = [NSString stringWithFormat:@"%.4f", answer];

This tells XCode to display your number with 4 decimal places, but it doesn't try to "pad" the front of the number with spaces. For example:

1.23 ->  "    1.2300"   //  When using [NSString stringWithFormat:@"%9.4f", answer];
1.23 ->  "1.2300"       //  When using [NSString stringWithFormat:@"%.4f", answer];

try something like this

label.text = [NSString stringWithFormat:@"%9.4f", answer];

where the 9 means total digits (in terms of padding for alignment), and the 4 means 4 decimal places.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!