I have an NSDecimalNumber representing the amount of money. I want to print it as "999,999,999,999,999,999,99", regardless of language. How to do it?
NSNumberFormatter prints me 1,000,000,000,000,000,000,000.00 instead (it seems like Apple engineers never developed an iPhone for a platform for financial software).
[NSDecimalNumber description] and [NSDecimalNumber descriptionWithLocale] both print the correct value. How to format the result, with the grouping separator at @"\u2006" , the decimal separator at @"**,**" and exactly 2 decimal digits after the decimal separator?
Thanks in advance!
Update: Here is my solution, 10x to 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" ];
Sonts source share