Http://blog.sina.com.cn/s/blog_a2774bb10101293j.html
Today, my friend asked me a question, is how to just give up. Like float price = 0.126, how can I get 0.12?
Of course, the method of string interception can certainly achieve the same effect. But it's a simple question that can be judged and intercepted to get results, and it's always a bit awkward.
Here's a workaround for the problem:
-(NSString *) notrounding: (float) Price afterpoint: (int) position{
nsdecimalnumberhandler* Roundingbehavior = [Nsdecimalnumberhandler decimalnumberhandlerwithroundingmode: 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.
How to handle rounding issues in iOS