在項(xiàng)目中經(jīng)常使用到貨幣的結(jié)算問(wèn)題,但是貨幣的精度問(wèn)題真的很讓人頭疼~~不論你是用float類型還是double類型在累加的時(shí)候好像總是精度不夠呢
- 這里我們就使用到了
NSDecimalNumber
貨幣類了,初始化對(duì)象
NSDecimalNumber *decimal = [[NSDecimalNumber alloc]initWithString:string];
- 價(jià)格的累加,
decimalNumberByAdding:
。貨幣累的累加并不能像其他的基本數(shù)據(jù)類型似的 +=或者 ++,這里的計(jì)算只能使用一個(gè)NSDecimalNumber類型的對(duì)象承接上一個(gè)對(duì)象的數(shù)據(jù)。
NSDecimalNumber *totalPrice = [self getDecimalPriceWithNum:@"0"];
//計(jì)算總價(jià) 確保精度
NSDecimalNumber *getPrice = [self getDecimalPriceWithNum:[NSString stringWithFormat:@"%@",price]];
defaultPrice = totalPrice;
totalPrice = [defaultPrice decimalNumberByAdding:getPrice];```
