我有NSDecimalNumber
代表金额。
无论在哪里,我想将其打印为“999 999 999 999 999 999,00”。
我该怎么做?
NSNumberFormatter为我打印了1 000 000 000 000 000 000(相反,Apple工程师似乎从未将iPhone设计为财务软件的平台)。
[NSDecimalNumber description]
和[NSDecimalNumber descriptionWithLocale]
都打印正确的值。如何格式化结果,分组设置为@"\u2006"
,小数分隔符设置为@"**,**"
,小数分隔符后面恰好是2位小数?
提前致谢!
更新 这是我的解决方案,对Sulthan来说是10倍:
@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
答案 0 :(得分:6)
试试这个:
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;
答案 1 :(得分:3)
我遇到了同样的问题。我被告知NSNumberFormatter
首先将所有内容转换为double
。我是怎么解决的?这很容易,只需编写自己的格式化程序。