0

I'm trying to display values on website using

let chance = Math.pow(0.2, vict)*100;

The output gives dynamic value, and I need 0.16000000000000003% to show as 0.16% and 0.00025600000000000015% as 0.000256% and so on. How can I round it, so I'm not limited to fixed decimal number.

Edit: vict is a whole number at all times. I just need to remove the error as @Caltrop has stated in comments. chance should display the probability. I cannot use suggested option with .toFixed, because as I said, I don't want to be limited to fixed decimal number in dynamic value.

  • @benbotto That question does not seem related to this one. The user is asking how to display floats without accumulated error, which is not equivalent to rounding to a fixed number of decimal places. – Caltrop Jul 13 '22 at 14:41
  • Have you thought of using Decimal.js to avoid floating-point round-off errors? – qrsngky Jul 13 '22 at 14:41
  • `Number(0.16000000000000003).toFixed(2)` outputs `0.16`. No need for [decimal.js](https://mikemcl.github.io/decimal.js/) yet, though I have used it too, it's pretty cool. – Peter Krebs Jul 13 '22 at 14:43
  • What if the number went on like this: `0.02123917198656`.. where should the cut-off point be? It is easy to cut off zeros at the end, but other numbers exist as well. Please update the question what should happen with those. – Peter Krebs Jul 13 '22 at 14:48
  • @PeterKrebs Updated, there won't be numbers like this since vect is a whole number – Karol Pilch Jul 13 '22 at 14:55
  • Ok I have an Idea what you mean. I'll post once reopened. – Peter Krebs Jul 13 '22 at 15:08
  • 1
    I guess this won't be reopened soon. If you know what I mean, use a regular expression to remove the later part of the number: `chance.toString().replace(/^(\d+\.0*[1-9]*).+/, '$1')` – Peter Krebs Jul 14 '22 at 12:37
  • Got it, that solves it. First post on stackoverflow, guess I will have to learn to specify few times more thoroughly. Thank you – Karol Pilch Jul 14 '22 at 15:53

0 Answers0