Formatting decimal

Asked

Viewed 285 times

5

I’m having a problem formatting decimals in my code in Objective-c, I would like to take advantage only 2 decimal places of my variable which is float.

Ex: Value of the variable discount = 4.00043621

and I need it stored only 4.00

I could format only with StringWithFormat, as the example below:

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

thus the value of the variable decimalFormatado was the way I wanted "4.00" however, in String. and I need it to continue in float, because I’ll need to use it as float in a conditional structure further ahead.

Any suggestions for how best to do this?

I am looking for a way to enjoy only the 2 houses after the comma with a direct format, convert from string for decimal with the two houses I believe is not a good practice.

  • 1

    You speak in decimal but are using a float. Apparently you’re using it for things that involve money. Are you sure you want to do this? Don’t you think it’s strange that the value is 4.00043621? If you do an account with this, you know it will give unexpected results and they are usually considered wrong?

  • 1

    I just realized friend, I will use rounding instead of truncate, thank you very much! reply there that already positive you!

  • 1

    But if you still use the number for calculations just keep it in the original variable... For the formatted number normally declare as Nsstring in another variable as it is already being done..

1 answer

5


Formatting should be done as string same. Formatted numbers are texts to be presented, so this is the correct type.

What you want is not formatting, you want to get the exact value, and this is not possible with the type float.

Normally I wouldn’t even answer and close as a duplicate because there are so many questions on the subject here but still didn’t exist about 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 treats decimally the number you need to treat. float is not decimal, is binary.

Rounding doesn’t solve the problem, it just disguises it.

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.