gpt4 book ai didi

iphone - iOS : formatting decimal numbers

转载 作者:搜寻专家 更新时间:2023-10-30 19:55:20 29 4
gpt4 key购买 nike

我有一个代表金额的 NSDecimalNumber。我想将其打印为“999 999 999 999 999 999,00”,而不管语言环境如何。我该怎么做?

NSNumberFormatter 打印出 1 000 000 000 000 000 000,00(似乎 Apple 工程师从未将 iPhone 设计为财务软件平台)。

[NSDecimalNumber description][NSDecimalNumber descriptionWithLocale] 都打印出正确的值。如何格式化结果,将分组分隔符设置为 @"\u2006",将小数点分隔符设置为 @"**,**",并且在后面正好是 2 位小数小数分隔符?

提前致谢!

更新:这是我的解决方案,10 倍于 Sulthan:

@implementation NSDecimalNumber(MiscUtils)

-(NSString*)moneyToString
{
static NSDecimalNumberHandler* s_handler = nil;
if( !s_handler )
s_handler = [ [ NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO ] retain ];

NSDecimalNumber *dec = [ self decimalNumberByRoundingAccordingToBehavior:s_handler ];
NSString* str = [ dec description ];
NSRange rDot = [ str rangeOfString:@"." ];
int nIntDigits = str.length;
int nFracDigits = 0;
if( rDot.length > 0 )
{
nIntDigits = rDot.location;
nFracDigits = str.length - ( rDot.location + 1 );
}
int nGroupSeparators = ( nIntDigits - 1 ) / 3;

NSMutableString* res = [ NSMutableString stringWithCapacity:nIntDigits + nGroupSeparators + 3 ];
NSString *groupingSeparator = @"\u2006";

int nFirstGroup = ( nIntDigits % 3 );
int nextInd = 0;
if( nFirstGroup )
{
[ res appendString:[ str substringToIndex:nFirstGroup ] ];
nextInd = nFirstGroup;
}

while( nextInd < nIntDigits )
{
if( res.length > 0 )
[ res appendString:groupingSeparator ];
[ res appendString:[ str substringWithRange:NSMakeRange( nextInd, 3 ) ] ];
nextInd += 3;
}

if( nFracDigits > 0 )
{
if( nFracDigits > 2 )
nFracDigits = 2;
[ res appendString:@"," ];
[ res appendString:[ str substringWithRange:NSMakeRange( rDot.location + 1, nFracDigits ) ] ];
while( nFracDigits < 2 )
{
[ res appendString:@"0" ];
nFracDigits++;
}
}
else
[ res appendString:@",00" ];
// DLog( "formatDecimal: %@ -> %@", dec, res );
return res;
}
@end

最佳答案

试试这个:

    NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"US"];

NSNumberFormatter *frm = [[NSNumberFormatter alloc] init];
[frm setNumberStyle:NSNumberFormatterDecimalStyle];
[frm setMaximumFractionDigits:2];
[frm setMinimumFractionDigits:2];
[frm setLocale:usLocale];
NSString *formattedNumberStr = [frm stringFromNumber:[NSNumber numberWithFloat:floatToRound]];

[frm release];
[usLocale release];

return formattedNumberStr;

关于iphone - iOS : formatting decimal numbers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9385783/

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