----Rounding issues for iOS development

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.