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.
5 Answers
It's working :
var p = 8.8 - 5;
console.log(p.toFixed(1)); 
    
    - 1,549
- 14
- 27
- 
                    You can check it now – Jigar7521 Nov 04 '16 at 05:04
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>
 
    
    - 7,611
- 2
- 15
- 17
- 
                    
- 
                    @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
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); 
    
    - 199
- 2
- 5
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> 
    
    - 19,238
- 3
- 22
- 49
 
    
