0

My app calculated like this.

float containTaxValue = 840;
float taxRate = 5;
float divisionedNum = (100 + taxRate)/100;
float removedTaxValue = containTaxValue/divisionedNum;
float taxValue = containTaxValue - removedTaxValue;

finally the answer is

NSLog(@"%f",removedTaxValue); => 800.000061
NSLog(@"%f",containTaxValue); => 840.000000
NSLog(@"%f",taxValue); => 39.999939

I would like to get "taxValue == 40.000000" in this code.

I couldn't make sense what's issue. Let me know any advise please.

Takuya Takahashi
  • 453
  • 1
  • 4
  • 16

4 Answers4

2

The IEEE 754 standard is a way of storing floating-point numbers in an easy to manipulate way by the machine. This method is used by the INtel and mot of the processors.

IEEE 754 specifies that numbers be stored in binary format to reduce storage requirements and allow the built-in binary arithmetic instructions that are available on all microprocessors to process the data in a relatively rapid fashion. However, some numbers that are simple, non-repeating decimal numbers are converted into repeating binary numbers that cannot be stored with perfect accuracy.

1/10 can be represented in Decimal form .1

But In Binary form it Becomes: .0001100011000111000111 (and so on)

And Hence the rounding-off error occurs.

You have to convert it to int to round it off.

The Binary Conversion of 1.05 also goes on 00111111 10000110 01100110 01100110....

Abhishek Singh
  • 6,068
  • 1
  • 23
  • 25
1

float cannot exactly represent many values, for example 1.05. Rounding errors occur and carry forward to the final result.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
0

If you're not sure how long your number after dot, you can use %.6f instead simple %f to print exact 6 digits after dot, to round up the values you can use ceil(double) function, It will round up the values.

with %f only,

float taxValue = 39.999999; // you've 6 digits after dot
NSLog(@"%f",ceil(taxValue));

Output, 40.000000

with %.6f,

float taxValue = 39.99; // you've only 2 digits after dot but still you want to show 6 digit
NSLog(@"%.6f",ceil(taxValue));

Output, 40.000000

Hemang
  • 26,840
  • 19
  • 119
  • 186
  • As per OP **I would like to get "taxValue == 40.000000" in this code.** – Anoop Vaidya Mar 18 '13 at 08:44
  • @AnoopVaidya, Yes, I was missed that! Please check my updated answer. Is it valid now? – Hemang Mar 19 '13 at 05:26
  • @CarlVeazey, thanks for the info! I've no idea about financial code, however I used to do this tricks for get the expected result! Please check my updated answer :) – Hemang Mar 19 '13 at 05:27
0

To round up float Values you can use following code

float A,B; // this variables have to be floats!
int roundDown = floor(A/B); // rounded down
int roundUp = ceil(A/B); // rounded Up
int rounded = lroundf(theFloat); //rounded

The result int value is converted again to float

Hope this Helps !!!

Vishnu
  • 2,243
  • 2
  • 21
  • 44