2

Here i have a problem in my web application(tested on chrome and firefox and nodejs):

when i run (1.2 - 1) it returns 0.19999999999999996 as result.

does anyone know why?

Behrad Farsi
  • 1,110
  • 13
  • 25

2 Answers2

3

you can solve your problem: (1.2 - 1).toFixed(1) * 1 // 0.2

Mehdi Emrani
  • 1,313
  • 2
  • 14
  • 26
1

you can use toFixed method of javascript more detail:

Method of Number

Implemented in JavaScript 1.5

ECMAScript Edition ECMAScript 3rd Edition

Syntax

number.toFixed( [digits] )

Parameter

digits The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.

Returns

A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If number is greater than 1e+21, this method simply calls Number.toString() and returns a string in exponential notation.

Throws

RangeError If digits is too small or too large. Values between 0 and 20, inclusive, will not cause a RangeError. Implementations are allowed to support larger and smaller values as well. TypeError If this method is invoked on an object that is not a Number.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toFixed

Omid Shariati
  • 1,904
  • 5
  • 22
  • 44