gpt4 book ai didi

objective-c - 将 float 格式化为 NSString 时截断多余的零

转载 作者:行者123 更新时间:2023-12-03 16:51:30 25 4
gpt4 key购买 nike

我正在尝试格式化一些float,如下所示:

1.1500 将显示为“$ 1.15”
1.1000 将显示为“$ 1.10”
1.0000 将显示为“$ 1.00”
1.4710 将显示为“$ 1.471”
1.4711 将显示为“$ 1.4711”

我尝试过

NSString *answer = [NSString stringWithFormat:@"$ %.2f",myvalue];

最佳答案

这正是NSNumberFormatters用于:

float onefifteen = 1.1500;    // displayed as “$ 1.15”
float oneten = 1.1000; // displayed as “$ 1.10”
float one = 1.0000; // displayed as “$ 1.00”
float onefortyseventen = 1.4710; // displayed as “$ 1.471”
float onefortyseveneleven = 1.4711; // displayed as “$ 1.4711”

NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setUsesSignificantDigits:YES];
// The whole number counts as the first "significant digit"
[formatter setMinimumSignificantDigits:3];

NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:onefifteen]]);
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:oneten]]);
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:one]]);
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:onefortyseventen]]);
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:onefortyseveneleven]]);

2011-12-15 19:36:52.185 SignificantCents[49282:903] $1.15
2011-12-15 19:36:52.190 SignificantCents[49282:903] $1.10
2011-12-15 19:36:52.190 SignificantCents[49282:903] $1.00
2011-12-15 19:36:52.191 SignificantCents[49282:903] $1.471
2011-12-15 19:36:52.192 SignificantCents[49282:903] $1.4711

关于objective-c - 将 float 格式化为 NSString 时截断多余的零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8518603/

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