0

I have

var x = 100;
var y = 10;
var b = 10 /100 + 1;
var z = b*50

Expect z = 55. But I got z = 55.0000000001. I don't know why. How do I fix it in Javascript. Thanks

Pang
  • 9,564
  • 146
  • 81
  • 122
Juong David
  • 101
  • 1
  • 8
  • 1
    What does `x` and `y` have to do with the rest of the code? – Pang Dec 23 '16 at 06:50
  • That's the nature of Javascript as we know it. You either live with it, parsing, rounding, formatting time and time again, or use a numeric (math) library. – vothaison Dec 23 '16 at 07:01

2 Answers2

1

Use:

z = parseInt(z);

It will treat z as int.

Nurjan
  • 5,889
  • 5
  • 34
  • 54
0

Use toFixed for digits after the decimal point. Default is 0.

var x = 100;
var y = 10;
var b = 10 /100 + 1;
var z = b*50;

alert(z.toFixed(0));
alert(z.toFixed()); //both are same

For more reference : http://www.w3schools.com/jsref/jsref_tofixed.asp

Divyesh Kanzariya
  • 3,629
  • 3
  • 43
  • 44