Double, float types often have unpredictable problems when you need to calculate accurately in iOS:
During debugging, you can see that the Doule type D3 the value is not expected to be 9999.99 during the calculation.
If important data, such as amounts, are not recommended for use in a way that does not recommend using this kind of uncontrolled results, you can use another type of data nsdecimalnumber that iOS provides to support accurate accuracy calculations.
Nsdecimalnumber is a subclass of NSNumber, more powerful than NSNumber, can specify a number of powers, rounding, and so on. Due to the high accuracy of the nsdecimalnumber, it is more time-consuming than the basic data type, so it is important to weigh in, and Apple recommends that it be used in currencies as well as in scenarios that require high precision.
All Nsdecimalnumber objects are immutable, which means that they cannot be changed after they have been created.
-(Nsdecimalnumber *) decimalnumberbyadding: (Nsdecimalnumber *) decimalnumber;-(Nsdecimalnumber *) Decimalnumberbyadding: (Nsdecimalnumber *) Decimalnumber Withbehavior: (Nullable ID <NSDecimalNumberBehaviors>) behavior;-(Nsdecimalnumber *) decimalnumberbysubtracting: (Nsdecimalnumber *) decimalnumber;-(NSDecimalNumber *) Decimalnumberbysubtracting: (Nsdecimalnumber *) Decimalnumber Withbehavior: (Nullable ID <nsdecimalnumberbehaviors >) behavior;-(Nsdecimalnumber *) Decimalnumberbymultiplyingby: (Nsdecimalnumber *) decimalnumber;-( Nsdecimalnumber *) Decimalnumberbymultiplyingby: (Nsdecimalnumber *) Decimalnumber Withbehavior: (Nullable ID < nsdecimalnumberbehaviors>) behavior;-(Nsdecimalnumber *) Decimalnumberbydividingby: (NSDecimalNumber *) decimalnumber;-(Nsdecimalnumber *) Decimalnumberbydividingby: (Nsdecimalnumber *) Decimalnumber WithBehavior: ( Nullable ID <NSDecimalNumberBehaviors>) behavior;
The Nsdecimalnumberbehaviors object can be created by the following methods
Nsdecimalnumberhandler *roundup = [Nsdecimalnumberhandler decimalnumberhandlerwithroundingmode:nsroundbankers scale:2 raiseonexactness:no raiseonoverflow:no raiseonunderflow:no Raiseondividebyzero: YES];
The scale represents the retention of several decimal places
Enumeration
Nsroundplain, //Round up on a tie//seemingly take the whole nsrounddown, //always down = = truncate //Only in nsroundup , //Always up //Only into nsroundbankers //on a tie round so last digit is even seemingly rounded
Objective-c Accurate Calculation