PHP float calculation error when subtracting
I have a very strange issue. If I subtract 2 float vars where one is the result of a mathematical operation I get a wrong value.
Example:
var_dump($remaining);
var_dump($this->hours_sub['personal']);
echo $remaining-$this->hours_sub['personal'];
This it the output:
float 5.4
float 1.4
5.3290705182008E-15
5.4-1.4 should be 4
If I add the two values the result is correct.
Where is my mistake?
It can not be a rounding issue.
php math floating-point formatting
|
show 3 more comments
I have a very strange issue. If I subtract 2 float vars where one is the result of a mathematical operation I get a wrong value.
Example:
var_dump($remaining);
var_dump($this->hours_sub['personal']);
echo $remaining-$this->hours_sub['personal'];
This it the output:
float 5.4
float 1.4
5.3290705182008E-15
5.4-1.4 should be 4
If I add the two values the result is correct.
Where is my mistake?
It can not be a rounding issue.
php math floating-point formatting
1
It is working fine, maybe you should trybcsub()
– HamZa
Jun 20 '13 at 10:11
Why "It can not be a rounding issue."?
– Patricia Shanahan
Jun 20 '13 at 10:37
1
@PatriciaShanahan Because a rounding issue would not produce a value close to 0 for the difference of two approximations to 5.4 and 1.4 respectively. A "rounding issue" would produce3.999...9xyz
or4.000...0xyz
.
– Daniel Fischer
Jun 20 '13 at 12:10
Does a direct$a=5.4;$b=1.4;echo $a-$b;
produce the same wrong result?
– Jürgen Thelen
Jun 20 '13 at 12:31
2
@WouterJ At the moment, I'm not convinced the question should be closed at all. I suspect it will be TL, but I'm not sure. What I'm sure of is that it's not a dupe of what it was closed of. Not in the remotest.
– Daniel Fischer
Jun 20 '13 at 21:55
|
show 3 more comments
I have a very strange issue. If I subtract 2 float vars where one is the result of a mathematical operation I get a wrong value.
Example:
var_dump($remaining);
var_dump($this->hours_sub['personal']);
echo $remaining-$this->hours_sub['personal'];
This it the output:
float 5.4
float 1.4
5.3290705182008E-15
5.4-1.4 should be 4
If I add the two values the result is correct.
Where is my mistake?
It can not be a rounding issue.
php math floating-point formatting
I have a very strange issue. If I subtract 2 float vars where one is the result of a mathematical operation I get a wrong value.
Example:
var_dump($remaining);
var_dump($this->hours_sub['personal']);
echo $remaining-$this->hours_sub['personal'];
This it the output:
float 5.4
float 1.4
5.3290705182008E-15
5.4-1.4 should be 4
If I add the two values the result is correct.
Where is my mistake?
It can not be a rounding issue.
php math floating-point formatting
php math floating-point formatting
asked Jun 20 '13 at 10:02
RubbelDeCatcRubbelDeCatc
391159
391159
1
It is working fine, maybe you should trybcsub()
– HamZa
Jun 20 '13 at 10:11
Why "It can not be a rounding issue."?
– Patricia Shanahan
Jun 20 '13 at 10:37
1
@PatriciaShanahan Because a rounding issue would not produce a value close to 0 for the difference of two approximations to 5.4 and 1.4 respectively. A "rounding issue" would produce3.999...9xyz
or4.000...0xyz
.
– Daniel Fischer
Jun 20 '13 at 12:10
Does a direct$a=5.4;$b=1.4;echo $a-$b;
produce the same wrong result?
– Jürgen Thelen
Jun 20 '13 at 12:31
2
@WouterJ At the moment, I'm not convinced the question should be closed at all. I suspect it will be TL, but I'm not sure. What I'm sure of is that it's not a dupe of what it was closed of. Not in the remotest.
– Daniel Fischer
Jun 20 '13 at 21:55
|
show 3 more comments
1
It is working fine, maybe you should trybcsub()
– HamZa
Jun 20 '13 at 10:11
Why "It can not be a rounding issue."?
– Patricia Shanahan
Jun 20 '13 at 10:37
1
@PatriciaShanahan Because a rounding issue would not produce a value close to 0 for the difference of two approximations to 5.4 and 1.4 respectively. A "rounding issue" would produce3.999...9xyz
or4.000...0xyz
.
– Daniel Fischer
Jun 20 '13 at 12:10
Does a direct$a=5.4;$b=1.4;echo $a-$b;
produce the same wrong result?
– Jürgen Thelen
Jun 20 '13 at 12:31
2
@WouterJ At the moment, I'm not convinced the question should be closed at all. I suspect it will be TL, but I'm not sure. What I'm sure of is that it's not a dupe of what it was closed of. Not in the remotest.
– Daniel Fischer
Jun 20 '13 at 21:55
1
1
It is working fine, maybe you should try
bcsub()
– HamZa
Jun 20 '13 at 10:11
It is working fine, maybe you should try
bcsub()
– HamZa
Jun 20 '13 at 10:11
Why "It can not be a rounding issue."?
– Patricia Shanahan
Jun 20 '13 at 10:37
Why "It can not be a rounding issue."?
– Patricia Shanahan
Jun 20 '13 at 10:37
1
1
@PatriciaShanahan Because a rounding issue would not produce a value close to 0 for the difference of two approximations to 5.4 and 1.4 respectively. A "rounding issue" would produce
3.999...9xyz
or 4.000...0xyz
.– Daniel Fischer
Jun 20 '13 at 12:10
@PatriciaShanahan Because a rounding issue would not produce a value close to 0 for the difference of two approximations to 5.4 and 1.4 respectively. A "rounding issue" would produce
3.999...9xyz
or 4.000...0xyz
.– Daniel Fischer
Jun 20 '13 at 12:10
Does a direct
$a=5.4;$b=1.4;echo $a-$b;
produce the same wrong result?– Jürgen Thelen
Jun 20 '13 at 12:31
Does a direct
$a=5.4;$b=1.4;echo $a-$b;
produce the same wrong result?– Jürgen Thelen
Jun 20 '13 at 12:31
2
2
@WouterJ At the moment, I'm not convinced the question should be closed at all. I suspect it will be TL, but I'm not sure. What I'm sure of is that it's not a dupe of what it was closed of. Not in the remotest.
– Daniel Fischer
Jun 20 '13 at 21:55
@WouterJ At the moment, I'm not convinced the question should be closed at all. I suspect it will be TL, but I'm not sure. What I'm sure of is that it's not a dupe of what it was closed of. Not in the remotest.
– Daniel Fischer
Jun 20 '13 at 21:55
|
show 3 more comments
3 Answers
3
active
oldest
votes
If still somebody reach this page with similar problems where floating number subtraction causes error or strange values.
I want to explain this problem with a bit more details.
It is not directly related to PHP and it is not a bug.
However, every programmer should be aware of this issue.
This problem even took many lives two decades ago.
On 25 February 1991 this problem in floating number calculation in a MIM-104 Patriot missile battery prevented it intercepting an incoming Scud missile in Dhahran, Saudi Arabia, contributing to the death of 28 soldiers from the U.S. Army's 14th Quartermaster Detachment.
But why it happens?
The reason is that floating point values represent a limited precision. So, a value might
not have the same string representation after any processing. It also
includes writing a floating point value in your script and directly
printing it without any mathematical operations.
Just a simple example:
$a = '36';
$b = '-35.99';
echo ($a + $b);
You would expect it to print 0.01
, right?
But it will print a very strange answer like 0.009999999999998
Like other numbers, floating point numbers double or float is stored in memory as a string of 0's and 1's. How floating point differs from integer is in how we interpret the 0's and 1's when we want to look at them. There are many standards how they are stored.
Floating-point numbers are typically packed into a computer datum as the sign bit, the exponent field, and the significand or mantissa, from left to right....
Decimal numbers are not well represented in binary due to lack of enough space. So, you can't express 1/3
exactly as it's 0.3333333...
, right? Why we can't represent 0.01
as a binary float number is for the same reason. 1/100
is 0.00000010100011110101110000.....
with a repeating 10100011110101110000
.
If 0.01
is kept in simplified and system-truncated form of 01000111101011100001010
in binary, when it is translated back to decimal, it would be read like 0.0099999....
depending on system (64bit computers will give you much better precision than 32-bits). Operating system decides in this case whether to print it as it sees or how to make it in more human-readable way. So, it is machine-dependent how they want to represent it. But it can be protected in language level with different methods.
If you format the result using
echo number_format(0.009999999999998, 2);
it will print 0.01
.
It is because in this case you instruct how it should be read and how precision you require.
Thanks for the good answer.
– RubbelDeCatc
Mar 3 '15 at 12:59
how to fix this ?
– mrid
Mar 22 '18 at 7:16
1
Decades will go and I will always say that this is an OBVIOUS BUG. We don't care if it saves with0
and1
combination or whetever - The inventors should had invented solution for this, without forcing us to learn custom programming for just to calculate36-35.99
(i.e. save it as string at first and convert back to number - we just don't care. We need computer to calculate the simple things correctly, without any need to know the internals offloat
) .
– T.Todua
Jul 2 '18 at 16:57
I have already spent hour to just get the answer945252744562139136 - 1
, searched google several times for a code which can just get that simple answer correctly inphp
but haven't yet found.
– T.Todua
Jul 2 '18 at 17:06
add a comment |
In addition to using number_format(), there are three other ways to obtain the correct result. One involves doing a little math, as follows:
<?php
$a = '36';
$b = '-35.99';
$a *= 100;
$b *= 100;
echo (($a + $b)/100),"n";
See demo
Or, you could simply use printf():
<?php
$a = '36';
$b = '-35.99';
printf("n%.2f",($a+$b));
See demo
Note, without the precision specifier, the printf() result will contain trailing zero decimals, as follows: 0.010000
You also could also utilize the BC Math function bcadd(), as follows:
<?php
$a = '36';
$b = '-35.99';
echo "n",bcadd($a,$b,2);
See demo
add a comment |
This worked for me:
<?php
$a = 96.35;
$b = 96.01;
$c = ( ( floor($a * 100) - floor($b * 100) ) / 100 );
echo $c; // should see 0.34 exactly instead of 0.33999999999999
?>
Since the problem occurs with floating point subtraction operation I decided to eliminate that by transforming it into an integer operation, then backing up the result into a floating point again.
I much prefer that solution because basically it does prevent the error on calculation rather than rouding up the result with other functions.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17210787%2fphp-float-calculation-error-when-subtracting%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
If still somebody reach this page with similar problems where floating number subtraction causes error or strange values.
I want to explain this problem with a bit more details.
It is not directly related to PHP and it is not a bug.
However, every programmer should be aware of this issue.
This problem even took many lives two decades ago.
On 25 February 1991 this problem in floating number calculation in a MIM-104 Patriot missile battery prevented it intercepting an incoming Scud missile in Dhahran, Saudi Arabia, contributing to the death of 28 soldiers from the U.S. Army's 14th Quartermaster Detachment.
But why it happens?
The reason is that floating point values represent a limited precision. So, a value might
not have the same string representation after any processing. It also
includes writing a floating point value in your script and directly
printing it without any mathematical operations.
Just a simple example:
$a = '36';
$b = '-35.99';
echo ($a + $b);
You would expect it to print 0.01
, right?
But it will print a very strange answer like 0.009999999999998
Like other numbers, floating point numbers double or float is stored in memory as a string of 0's and 1's. How floating point differs from integer is in how we interpret the 0's and 1's when we want to look at them. There are many standards how they are stored.
Floating-point numbers are typically packed into a computer datum as the sign bit, the exponent field, and the significand or mantissa, from left to right....
Decimal numbers are not well represented in binary due to lack of enough space. So, you can't express 1/3
exactly as it's 0.3333333...
, right? Why we can't represent 0.01
as a binary float number is for the same reason. 1/100
is 0.00000010100011110101110000.....
with a repeating 10100011110101110000
.
If 0.01
is kept in simplified and system-truncated form of 01000111101011100001010
in binary, when it is translated back to decimal, it would be read like 0.0099999....
depending on system (64bit computers will give you much better precision than 32-bits). Operating system decides in this case whether to print it as it sees or how to make it in more human-readable way. So, it is machine-dependent how they want to represent it. But it can be protected in language level with different methods.
If you format the result using
echo number_format(0.009999999999998, 2);
it will print 0.01
.
It is because in this case you instruct how it should be read and how precision you require.
Thanks for the good answer.
– RubbelDeCatc
Mar 3 '15 at 12:59
how to fix this ?
– mrid
Mar 22 '18 at 7:16
1
Decades will go and I will always say that this is an OBVIOUS BUG. We don't care if it saves with0
and1
combination or whetever - The inventors should had invented solution for this, without forcing us to learn custom programming for just to calculate36-35.99
(i.e. save it as string at first and convert back to number - we just don't care. We need computer to calculate the simple things correctly, without any need to know the internals offloat
) .
– T.Todua
Jul 2 '18 at 16:57
I have already spent hour to just get the answer945252744562139136 - 1
, searched google several times for a code which can just get that simple answer correctly inphp
but haven't yet found.
– T.Todua
Jul 2 '18 at 17:06
add a comment |
If still somebody reach this page with similar problems where floating number subtraction causes error or strange values.
I want to explain this problem with a bit more details.
It is not directly related to PHP and it is not a bug.
However, every programmer should be aware of this issue.
This problem even took many lives two decades ago.
On 25 February 1991 this problem in floating number calculation in a MIM-104 Patriot missile battery prevented it intercepting an incoming Scud missile in Dhahran, Saudi Arabia, contributing to the death of 28 soldiers from the U.S. Army's 14th Quartermaster Detachment.
But why it happens?
The reason is that floating point values represent a limited precision. So, a value might
not have the same string representation after any processing. It also
includes writing a floating point value in your script and directly
printing it without any mathematical operations.
Just a simple example:
$a = '36';
$b = '-35.99';
echo ($a + $b);
You would expect it to print 0.01
, right?
But it will print a very strange answer like 0.009999999999998
Like other numbers, floating point numbers double or float is stored in memory as a string of 0's and 1's. How floating point differs from integer is in how we interpret the 0's and 1's when we want to look at them. There are many standards how they are stored.
Floating-point numbers are typically packed into a computer datum as the sign bit, the exponent field, and the significand or mantissa, from left to right....
Decimal numbers are not well represented in binary due to lack of enough space. So, you can't express 1/3
exactly as it's 0.3333333...
, right? Why we can't represent 0.01
as a binary float number is for the same reason. 1/100
is 0.00000010100011110101110000.....
with a repeating 10100011110101110000
.
If 0.01
is kept in simplified and system-truncated form of 01000111101011100001010
in binary, when it is translated back to decimal, it would be read like 0.0099999....
depending on system (64bit computers will give you much better precision than 32-bits). Operating system decides in this case whether to print it as it sees or how to make it in more human-readable way. So, it is machine-dependent how they want to represent it. But it can be protected in language level with different methods.
If you format the result using
echo number_format(0.009999999999998, 2);
it will print 0.01
.
It is because in this case you instruct how it should be read and how precision you require.
Thanks for the good answer.
– RubbelDeCatc
Mar 3 '15 at 12:59
how to fix this ?
– mrid
Mar 22 '18 at 7:16
1
Decades will go and I will always say that this is an OBVIOUS BUG. We don't care if it saves with0
and1
combination or whetever - The inventors should had invented solution for this, without forcing us to learn custom programming for just to calculate36-35.99
(i.e. save it as string at first and convert back to number - we just don't care. We need computer to calculate the simple things correctly, without any need to know the internals offloat
) .
– T.Todua
Jul 2 '18 at 16:57
I have already spent hour to just get the answer945252744562139136 - 1
, searched google several times for a code which can just get that simple answer correctly inphp
but haven't yet found.
– T.Todua
Jul 2 '18 at 17:06
add a comment |
If still somebody reach this page with similar problems where floating number subtraction causes error or strange values.
I want to explain this problem with a bit more details.
It is not directly related to PHP and it is not a bug.
However, every programmer should be aware of this issue.
This problem even took many lives two decades ago.
On 25 February 1991 this problem in floating number calculation in a MIM-104 Patriot missile battery prevented it intercepting an incoming Scud missile in Dhahran, Saudi Arabia, contributing to the death of 28 soldiers from the U.S. Army's 14th Quartermaster Detachment.
But why it happens?
The reason is that floating point values represent a limited precision. So, a value might
not have the same string representation after any processing. It also
includes writing a floating point value in your script and directly
printing it without any mathematical operations.
Just a simple example:
$a = '36';
$b = '-35.99';
echo ($a + $b);
You would expect it to print 0.01
, right?
But it will print a very strange answer like 0.009999999999998
Like other numbers, floating point numbers double or float is stored in memory as a string of 0's and 1's. How floating point differs from integer is in how we interpret the 0's and 1's when we want to look at them. There are many standards how they are stored.
Floating-point numbers are typically packed into a computer datum as the sign bit, the exponent field, and the significand or mantissa, from left to right....
Decimal numbers are not well represented in binary due to lack of enough space. So, you can't express 1/3
exactly as it's 0.3333333...
, right? Why we can't represent 0.01
as a binary float number is for the same reason. 1/100
is 0.00000010100011110101110000.....
with a repeating 10100011110101110000
.
If 0.01
is kept in simplified and system-truncated form of 01000111101011100001010
in binary, when it is translated back to decimal, it would be read like 0.0099999....
depending on system (64bit computers will give you much better precision than 32-bits). Operating system decides in this case whether to print it as it sees or how to make it in more human-readable way. So, it is machine-dependent how they want to represent it. But it can be protected in language level with different methods.
If you format the result using
echo number_format(0.009999999999998, 2);
it will print 0.01
.
It is because in this case you instruct how it should be read and how precision you require.
If still somebody reach this page with similar problems where floating number subtraction causes error or strange values.
I want to explain this problem with a bit more details.
It is not directly related to PHP and it is not a bug.
However, every programmer should be aware of this issue.
This problem even took many lives two decades ago.
On 25 February 1991 this problem in floating number calculation in a MIM-104 Patriot missile battery prevented it intercepting an incoming Scud missile in Dhahran, Saudi Arabia, contributing to the death of 28 soldiers from the U.S. Army's 14th Quartermaster Detachment.
But why it happens?
The reason is that floating point values represent a limited precision. So, a value might
not have the same string representation after any processing. It also
includes writing a floating point value in your script and directly
printing it without any mathematical operations.
Just a simple example:
$a = '36';
$b = '-35.99';
echo ($a + $b);
You would expect it to print 0.01
, right?
But it will print a very strange answer like 0.009999999999998
Like other numbers, floating point numbers double or float is stored in memory as a string of 0's and 1's. How floating point differs from integer is in how we interpret the 0's and 1's when we want to look at them. There are many standards how they are stored.
Floating-point numbers are typically packed into a computer datum as the sign bit, the exponent field, and the significand or mantissa, from left to right....
Decimal numbers are not well represented in binary due to lack of enough space. So, you can't express 1/3
exactly as it's 0.3333333...
, right? Why we can't represent 0.01
as a binary float number is for the same reason. 1/100
is 0.00000010100011110101110000.....
with a repeating 10100011110101110000
.
If 0.01
is kept in simplified and system-truncated form of 01000111101011100001010
in binary, when it is translated back to decimal, it would be read like 0.0099999....
depending on system (64bit computers will give you much better precision than 32-bits). Operating system decides in this case whether to print it as it sees or how to make it in more human-readable way. So, it is machine-dependent how they want to represent it. But it can be protected in language level with different methods.
If you format the result using
echo number_format(0.009999999999998, 2);
it will print 0.01
.
It is because in this case you instruct how it should be read and how precision you require.
edited Dec 20 '17 at 19:00
Phiter
9,611132858
9,611132858
answered Dec 18 '14 at 4:26
SelaySelay
2,2581717
2,2581717
Thanks for the good answer.
– RubbelDeCatc
Mar 3 '15 at 12:59
how to fix this ?
– mrid
Mar 22 '18 at 7:16
1
Decades will go and I will always say that this is an OBVIOUS BUG. We don't care if it saves with0
and1
combination or whetever - The inventors should had invented solution for this, without forcing us to learn custom programming for just to calculate36-35.99
(i.e. save it as string at first and convert back to number - we just don't care. We need computer to calculate the simple things correctly, without any need to know the internals offloat
) .
– T.Todua
Jul 2 '18 at 16:57
I have already spent hour to just get the answer945252744562139136 - 1
, searched google several times for a code which can just get that simple answer correctly inphp
but haven't yet found.
– T.Todua
Jul 2 '18 at 17:06
add a comment |
Thanks for the good answer.
– RubbelDeCatc
Mar 3 '15 at 12:59
how to fix this ?
– mrid
Mar 22 '18 at 7:16
1
Decades will go and I will always say that this is an OBVIOUS BUG. We don't care if it saves with0
and1
combination or whetever - The inventors should had invented solution for this, without forcing us to learn custom programming for just to calculate36-35.99
(i.e. save it as string at first and convert back to number - we just don't care. We need computer to calculate the simple things correctly, without any need to know the internals offloat
) .
– T.Todua
Jul 2 '18 at 16:57
I have already spent hour to just get the answer945252744562139136 - 1
, searched google several times for a code which can just get that simple answer correctly inphp
but haven't yet found.
– T.Todua
Jul 2 '18 at 17:06
Thanks for the good answer.
– RubbelDeCatc
Mar 3 '15 at 12:59
Thanks for the good answer.
– RubbelDeCatc
Mar 3 '15 at 12:59
how to fix this ?
– mrid
Mar 22 '18 at 7:16
how to fix this ?
– mrid
Mar 22 '18 at 7:16
1
1
Decades will go and I will always say that this is an OBVIOUS BUG. We don't care if it saves with
0
and 1
combination or whetever - The inventors should had invented solution for this, without forcing us to learn custom programming for just to calculate 36-35.99
(i.e. save it as string at first and convert back to number - we just don't care. We need computer to calculate the simple things correctly, without any need to know the internals of float
) .– T.Todua
Jul 2 '18 at 16:57
Decades will go and I will always say that this is an OBVIOUS BUG. We don't care if it saves with
0
and 1
combination or whetever - The inventors should had invented solution for this, without forcing us to learn custom programming for just to calculate 36-35.99
(i.e. save it as string at first and convert back to number - we just don't care. We need computer to calculate the simple things correctly, without any need to know the internals of float
) .– T.Todua
Jul 2 '18 at 16:57
I have already spent hour to just get the answer
945252744562139136 - 1
, searched google several times for a code which can just get that simple answer correctly in php
but haven't yet found.– T.Todua
Jul 2 '18 at 17:06
I have already spent hour to just get the answer
945252744562139136 - 1
, searched google several times for a code which can just get that simple answer correctly in php
but haven't yet found.– T.Todua
Jul 2 '18 at 17:06
add a comment |
In addition to using number_format(), there are three other ways to obtain the correct result. One involves doing a little math, as follows:
<?php
$a = '36';
$b = '-35.99';
$a *= 100;
$b *= 100;
echo (($a + $b)/100),"n";
See demo
Or, you could simply use printf():
<?php
$a = '36';
$b = '-35.99';
printf("n%.2f",($a+$b));
See demo
Note, without the precision specifier, the printf() result will contain trailing zero decimals, as follows: 0.010000
You also could also utilize the BC Math function bcadd(), as follows:
<?php
$a = '36';
$b = '-35.99';
echo "n",bcadd($a,$b,2);
See demo
add a comment |
In addition to using number_format(), there are three other ways to obtain the correct result. One involves doing a little math, as follows:
<?php
$a = '36';
$b = '-35.99';
$a *= 100;
$b *= 100;
echo (($a + $b)/100),"n";
See demo
Or, you could simply use printf():
<?php
$a = '36';
$b = '-35.99';
printf("n%.2f",($a+$b));
See demo
Note, without the precision specifier, the printf() result will contain trailing zero decimals, as follows: 0.010000
You also could also utilize the BC Math function bcadd(), as follows:
<?php
$a = '36';
$b = '-35.99';
echo "n",bcadd($a,$b,2);
See demo
add a comment |
In addition to using number_format(), there are three other ways to obtain the correct result. One involves doing a little math, as follows:
<?php
$a = '36';
$b = '-35.99';
$a *= 100;
$b *= 100;
echo (($a + $b)/100),"n";
See demo
Or, you could simply use printf():
<?php
$a = '36';
$b = '-35.99';
printf("n%.2f",($a+$b));
See demo
Note, without the precision specifier, the printf() result will contain trailing zero decimals, as follows: 0.010000
You also could also utilize the BC Math function bcadd(), as follows:
<?php
$a = '36';
$b = '-35.99';
echo "n",bcadd($a,$b,2);
See demo
In addition to using number_format(), there are three other ways to obtain the correct result. One involves doing a little math, as follows:
<?php
$a = '36';
$b = '-35.99';
$a *= 100;
$b *= 100;
echo (($a + $b)/100),"n";
See demo
Or, you could simply use printf():
<?php
$a = '36';
$b = '-35.99';
printf("n%.2f",($a+$b));
See demo
Note, without the precision specifier, the printf() result will contain trailing zero decimals, as follows: 0.010000
You also could also utilize the BC Math function bcadd(), as follows:
<?php
$a = '36';
$b = '-35.99';
echo "n",bcadd($a,$b,2);
See demo
edited Apr 29 '17 at 22:39
answered Apr 29 '17 at 22:04
slevy1slevy1
3,08011627
3,08011627
add a comment |
add a comment |
This worked for me:
<?php
$a = 96.35;
$b = 96.01;
$c = ( ( floor($a * 100) - floor($b * 100) ) / 100 );
echo $c; // should see 0.34 exactly instead of 0.33999999999999
?>
Since the problem occurs with floating point subtraction operation I decided to eliminate that by transforming it into an integer operation, then backing up the result into a floating point again.
I much prefer that solution because basically it does prevent the error on calculation rather than rouding up the result with other functions.
add a comment |
This worked for me:
<?php
$a = 96.35;
$b = 96.01;
$c = ( ( floor($a * 100) - floor($b * 100) ) / 100 );
echo $c; // should see 0.34 exactly instead of 0.33999999999999
?>
Since the problem occurs with floating point subtraction operation I decided to eliminate that by transforming it into an integer operation, then backing up the result into a floating point again.
I much prefer that solution because basically it does prevent the error on calculation rather than rouding up the result with other functions.
add a comment |
This worked for me:
<?php
$a = 96.35;
$b = 96.01;
$c = ( ( floor($a * 100) - floor($b * 100) ) / 100 );
echo $c; // should see 0.34 exactly instead of 0.33999999999999
?>
Since the problem occurs with floating point subtraction operation I decided to eliminate that by transforming it into an integer operation, then backing up the result into a floating point again.
I much prefer that solution because basically it does prevent the error on calculation rather than rouding up the result with other functions.
This worked for me:
<?php
$a = 96.35;
$b = 96.01;
$c = ( ( floor($a * 100) - floor($b * 100) ) / 100 );
echo $c; // should see 0.34 exactly instead of 0.33999999999999
?>
Since the problem occurs with floating point subtraction operation I decided to eliminate that by transforming it into an integer operation, then backing up the result into a floating point again.
I much prefer that solution because basically it does prevent the error on calculation rather than rouding up the result with other functions.
edited Nov 14 '18 at 16:23
quant
1,59211527
1,59211527
answered Nov 14 '18 at 13:31
mjaningmjaning
113
113
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17210787%2fphp-float-calculation-error-when-subtracting%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
It is working fine, maybe you should try
bcsub()
– HamZa
Jun 20 '13 at 10:11
Why "It can not be a rounding issue."?
– Patricia Shanahan
Jun 20 '13 at 10:37
1
@PatriciaShanahan Because a rounding issue would not produce a value close to 0 for the difference of two approximations to 5.4 and 1.4 respectively. A "rounding issue" would produce
3.999...9xyz
or4.000...0xyz
.– Daniel Fischer
Jun 20 '13 at 12:10
Does a direct
$a=5.4;$b=1.4;echo $a-$b;
produce the same wrong result?– Jürgen Thelen
Jun 20 '13 at 12:31
2
@WouterJ At the moment, I'm not convinced the question should be closed at all. I suspect it will be TL, but I'm not sure. What I'm sure of is that it's not a dupe of what it was closed of. Not in the remotest.
– Daniel Fischer
Jun 20 '13 at 21:55