Is there a way to suppress scientific notation for <input type="number">?
Asked Answered
P

2

22

I'd like to input numbers with up to eight decimal points with an <input> element. However, if I have an <input type="number" step="0.00000001"> and use the up/down arrows on the input element (on Chrome; here's the jsfiddle), then I get scientific notation for the small numbers:

enter image description here

If I input, say, 5, and then hit the arrow key, then scientific notation is suppressed:

enter image description here

Is there any way to get the browser to display the 1e-8 as 0.000000001?

Also, is there any danger here that with sufficiently small numbers, I'll hit floating point rounding errors?

<input type="number" step="0.00000001">
Pebrook answered 14/10, 2015 at 18:29 Comment(1)
Worth to mention that a number will not always be displayed in scientific notation. This answer explains when this will happen: https://mcmap.net/q/82450/-how-small-can-a-javascript-number-be-without-displaying-in-scientific-notationBarrier
G
12

<input oninput='precise(this)' type="number" step="0.00000001">

<script>
  function precise(elem) {
    elem.value = Number(elem.value).toFixed(8);
  }
</script>

You can change the toFixed parameter to the desired number of decimal digits as needed. I hope this helps!

Gravimetric answered 20/4, 2016 at 21:34 Comment(1)
you can pass the specific input element with oninput=precise(this), then doing function precise(el) { el.value = Number(el.value).toFixed(8); }Aultman
O
5

Here is a variation based on StardustGogeta's answer:

<input oninput="this.value=Number(this.value).toFixed(this.step.split('.')[1].length)" type=number step="0.00000001">
Override answered 9/9, 2017 at 13:48 Comment(1)
When you bind to oninput it works when you click the arrows next to the input field, but it doesn't let you type. If you replace oninput with onclick it lets you type and only modifies the content if you use the arrows.Crunch

© 2022 - 2024 — McMap. All rights reserved.