gpt4 book ai didi

ios - 如何使用 NSNumberFormatter 将数字格式化为有限字符的 NSString?

转载 作者:行者123 更新时间:2023-11-29 03:01:25 26 4
gpt4 key购买 nike

例如,计算器最多只能显示 9 个字符。

          1/2  ->        0.5
2/3 -> 0.6666667
3/4 -> 0.75
20000/3 -> 6666.6667
123456x123456 -> 1.5241E10
---------
123456789

最佳答案

NSNumberFormatter 上设置 setMaximumSignificantDigits:

 [numberFormatter setUsesSignificantDigits:YES];
[numberFormatter setMaximumSignificantDigits:9];
[numberFormatter setNumberStyle:NSNumberFormatterScientificStyle];

对于超过 9 位的整数,除了使用 NSNumberFormatterScientificStyle 之外,您无能为力。

用一个小程序(见下文)检查后 - 您仍然会遇到多位数指数的问题。您最好拥有多个 NSNumberFormatter 并在显示之前检查数字是多少。当我有更强大的解决方案时,我会快速尝试并更新它。

(直接从 CodeRunner 复制粘贴)

#import <Foundation/Foundation.h>

static void test(NSNumber *n)
{
NSNumberFormatter *f = [NSNumberFormatter new];
[f setUsesSignificantDigits:YES];
[f setMaximumSignificantDigits:9];
[f setNumberStyle:NSNumberFormatterScientificStyle];
NSString *s = [f stringFromNumber:n];
NSLog(@"%@ -> %@ (%lu)", n, s, [s length]);
}

int main(int argc, char *argv[]) {
@autoreleasepool {
test(@(1.0/2));
test(@(2.0/3));
test(@(3.0/4));
test(@(20000.0/2));
test(@(123456*123456));
test(@(0.000000000001));
test(@(123456789.000000000001));
test(@(12345.9999999999999));
}
}

输出

2014-04-24 12:33:01.480 Untitled[3006:507] 0.5 -> 5E-1 (4)
2014-04-24 12:33:01.481 Untitled[3006:507] 0.6666666666666666 -> 6.66666667E-1 (13)
2014-04-24 12:33:01.481 Untitled[3006:507] 0.75 -> 7.5E-1 (6)
2014-04-24 12:33:01.482 Untitled[3006:507] 10000 -> 1E4 (3)
2014-04-24 12:33:01.482 Untitled[3006:507] -1938485248 -> -1.93848525E9 (13)
2014-04-24 12:33:01.483 Untitled[3006:507] 1e-12 -> 1E-12 (5)
2014-04-24 12:33:01.483 Untitled[3006:507] 123456789 -> 1.23456789E8 (12)
2014-04-24 12:33:01.484 Untitled[3006:507] 12346 -> 1.2346E4 (8)

关于ios - 如何使用 NSNumberFormatter 将数字格式化为有限字符的 NSString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23266436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com