0

If one subtracts 5 from 8.8, the actual result is: 3.8 but in my code it gives 3.8000000007.
Why it this? Could anyone kindly provide a valuable insight?

Thanks in advance.

Poiz
  • 7,611
  • 2
  • 15
  • 17
Jaya
  • 3
  • 4

5 Answers5

1

It's working :

var p = 8.8 - 5;
console.log(p.toFixed(1));
Jigar7521
  • 1,549
  • 14
  • 27
0

In the below picture, Calculation part is there. Kindly Check it.

enter image description here

ChrisB
  • 2,497
  • 2
  • 24
  • 43
Jaya
  • 3
  • 4
0

The Javascript Engine is only trying to help you out. If it finds a Floating Point Number amongst the Numbers supplied in your Arithmetic Operations, it will automatically parse the Result to a Floating Point Number as well - (with the highest possible Precision).

Therefore, to get around this Eager but Unsolicited Help of the Javascript Engine; you'd need to manually call: toFixed() on the Resulting Value like so:

    var p = 8.8 - 5;
    console.log( p.toFixed(1) ); //<== 3.8

Alternatively, You may extend the Number Prototype and add your Unique Functionality if that is what you desire. However, this is not at all advised!!!

    <script type="text/javascript">

        Number.prototype.precise = function(){
            return this.toFixed(1);
        };

        Number.prototype.floatSubtract = function(num){
            return (this - num).toFixed(1);
        };

        var p1 = (8.8 - 5).precise();
        var p2 =  8.8.floatSubtract(5);

        console.log(p1);    //< 3.8
        console.log(p2);    //< 3.8
    </script>
Poiz
  • 7,611
  • 2
  • 15
  • 17
  • How to get exact add up value,without using .toFixed(). – Jaya Nov 04 '16 at 05:36
  • @Jaya As you can see; **this is a Javascript internal behaviour... a means of helping you out**. You may however add a Method to the Number Prototype (**not Advised**) to help do that for you. The Post has now been now updated to reflect this option as well. – Poiz Nov 04 '16 at 06:10
0

I think there is nothing wrong in using "toFixed()". Why you are looking for an answer without using it?

Nervertheless you could do it the mathematical way:

var result = (8.8 * 10  - 5 * 10) / 10;
console.log(result);
fatel
  • 199
  • 2
  • 5
0

Try this. I think this will be the solution.

<!doctype HTML>
<html>
  <head>
       <script>
      num = 8.8 - 5;
         console.log(Math.round(num * 100) / 100)
       </script>
    </head>
</html>
Nitheesh
  • 19,238
  • 3
  • 22
  • 49