How to use NSDecimalNumber?

前端 未结 4 564
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 00:51

I\'m building a app that needs to perform calculations on money.

I wonder how to properly use NSDecimalNumber, especially how to initialize it from integers, floats

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 00:54

    Design-wise, you should try to avoid converting NSDecimalNumber or NSDecimals to and from int, float, and double values for the same reasons it's recommended you use NSDecimalNumbers: loss of precision and binary floating point representation issues. I know, sometimes it's unavoidable (taking input from a slider, doing trigonometric calculations, etc.), but you should try to take input from users as NSStrings and then use initWithString:locale: or decimalNumberWithString:locale: to generate the NSDecimalNumbers. Do all your math with the NSDecimalNumbers and return their representation to users or save them to SQLite (or wherever) as their string description using descriptionWithLocale:.

    If you have to input from an int, float, or double, you could do something like the following:

    int myInt = 3;
    NSDecimalNumber *newDecimal = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%d", myInt]];
    

    or you could follow Ashley's suggestion to make sure you're safe in the decimal construction.

提交回复
热议问题