method One:
-(NSString *) notrounding: (float) Price afterpoint: (int) position{
nsdecimalnumberhandler* roundingbehavior = [ nsdecimalnumberhandler Decimalnumberhandlerwith roundingmode:nsrounddown scale:position raiseonexactness:no raiseonoverflow:no RaiseOnUnderflow:NO Raiseondividebyzero:no];
nsdecimalnumber *ouncesdecimal;
nsdecimalnumber *roundedounces;
ouncesdecimal = [[Nsdecimalnumber alloc] Initwithfloat:price ];
Roundedounces = [Ouncesdecimal decimalnumberbyroundingaccordingtobehavior: Roundingbehavior];
[Ouncesdecimal release];
return [nsstring stringwithformat:@ "%@", Roundedounces ];
}
Explain the parameters:
Price: Numbers that need to be processed,
Position: Keep the decimal point,
and then call
float s = 0.126;
NSString *sv = [self notrounding:s afterpoint:2 ];
NSLog (@ "SV =%@", SV );
The output is: SV = 0.12
The following describes the key parameters of Nsdecimalnumberhandler initialization: DecimalnumberhandlerwithRoundingmode:nsrounddown,
The Nsrounddown represents is only to be placed.
The parameter position of scale represents a few digits after the decimal point is retained.
What do I do if I just get into it, for example, float 0.162 want 0.17? , there is a table on the development document that is treated as a reserved decimal point. I believe that we can see the following:
Method Two:
round (12345.6789) result: 12346
round (12345.6789*100)/100 result: 12345.68
The second is the result I want, but I do not understand this simple rounding to make so complicated, there should be better, I remember in other languages with:round (12345.6789,2) You can achieve rounding to two decimal places.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
----Rounding issues with iOS development