-1

My javascript code is:

var a = 0.15;
var r = parseFloat(a.toFixed(1));
console.log(r)

This is not getting converted to 0.2.

Whereas other numbers like 0.25 are getting converted to 0.3, 0.45 to 0.5, 0.55 to 0.6, 0.65 to 0.7, 0.85 to 0.9 and so on.

Any solution to resolve this?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
chetana lotliker
  • 25
  • 1
  • 1
  • 3
  • Possible duplicate of [Round to at most 2 decimal places (only if necessary)](https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary), you just need to change it to 1 decimal – Mukyuu Nov 21 '19 at 06:12
  • can u plz provide syntax for the same ? – chetana lotliker Nov 21 '19 at 06:14
  • read the linked question and you find your question answered – Mukyuu Nov 21 '19 at 06:15
  • `0.35` will be `"0.3"` and `0.85` will be `"0.9"` - at least in Chrome und Firefox ([fiddle](https://jsfiddle.net/c87yoxqb/)) – Andreas Nov 21 '19 at 06:15
  • MDN has called out it might round up or down: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed#Description What's your goal? Are you trying to round to 1 decimal point? Maybe use `(Math.round(0.15 * 10)/10).toFixed(1)` instead? – Chuanqi Sun Nov 21 '19 at 06:19
  • https://stackoverflow.com/questions/12105787/tofixed-javascript-function-giving-strange-results# Check in this post behaviour is explained. – Shubhanu Sharma Nov 21 '19 at 06:20
  • @Chuanqi Sun Can u plz explain the logic behind this ? (Math.round(0.15 * 10)/10).toFixed(1) – chetana lotliker Nov 21 '19 at 06:35

1 Answers1

0

This is happening because floating point representation cannot be exact for some numbers.

You can use a library such as Big.js that has arbitrary precision to compute such values.

var a = Big("0.15");
console.log(a.toFixed(1));
<script src="https://cdn.jsdelivr.net/npm/big-js@3.1.3/big.js"></script>
Kraylog
  • 7,383
  • 1
  • 24
  • 35