Formatting Decimal

5

I'm having a problem decimally formatting my code in Objective-c, I'd like to take advantage of only 2 decimal places of my variable that is float .

Ex: Variable value discount = 4.00043621

I need to be stored only 4.00

I was able to format only with StringWithFormat , as the example below:

NSString* decimalFormatado = [NSString stringWithFormat: @"%.02f", discount];

In this way the value of the variable decimalFormatado was the way I wanted "4.00" but in String . and I need it to continue in float , since I will need to use it as float in a conditional structure later.

Any suggestions for how best to do this?

I'm looking for a way to take advantage of only the 2 boxes after the comma with a direct formatting, convert from string to decimal with both houses I think is not good practice.

    
asked by anonymous 21.08.2015 / 14:50

1 answer

4

Formatting must be done with% w / o% same. Formatted numbers are text to be displayed, so this is the correct type.

What you want is not formatting. You want to get the exact amount. And this is not possible with type string .

Normally I would not even answer and close as a duplicate because there are lots of questions on the subject here but I still did not exist on Objective-C. The "problem" is in the processor and affects all languages equally.

The solution is simple, if you need decimal information, use a type that decimally treats the number you need to treat. float is not decimal, it is binary.

Rounding does not solve the problem, it only disguises it.

Read more on other questions . But read it all, follow all the links . Learn why this is important to avoid harm to your users.

In this language the type is float . Some people prefer to work with integers. Rounding will still be necessary in both cases, but at least will be done in the right way. With a binary floating-point type you will always have bugs, even though in some cases it does not seem to have any.

    
21.08.2015 / 15:04