Reputation: 453
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.
Upvotes: 0
Views: 870
Reputation: 27072
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
Upvotes: 0
Reputation: 6166
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....
Upvotes: 2
Reputation: 2243
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 !!!
Upvotes: 0
Reputation: 81878
float
cannot exactly represent many values, for example 1.05. Rounding errors occur and carry forward to the final result.
Upvotes: 1