2

I'd like to force an <input type="number" step="0.01" /> to always have 2 decimals to enter accounting data.

I've managed to do that using JavaScript

document.getElementById('input').addEventListener('change', force2decimals);

function force2decimals(event) {
 event.target.value = Number(Math.round(event.target.value * 100) / 100).toFixed(2);
}
<input type="number" step="0.01" id="input" value="1.00" />

Is there any way to handle this natively?

I know about the step attribute, the "duplicate answer" doesn't reply to my question.

Yann Bertrand
  • 2,983
  • 1
  • 19
  • 37

2 Answers2

1

It could be done by this:

document.getElementById('input').addEventListener('change', force2decimals);

function force2decimals(event) {
 event.target.value = parseFloat(event.target.value).toFixed(2);
}
<input type="number" step="0.01" id="input" value="1.00" />

There is no way to do this "natively" in HTML5.

Yann Bertrand
  • 2,983
  • 1
  • 19
  • 37
Mojtaba
  • 4,326
  • 4
  • 17
  • 37
0

You can use this:

function force2decimals(event) {
  var value = $(event).val();
  var format_val = parseFloat(value).toFixed(2);
  $(event).val(format_val);
}
<input type="number" step="0.01" id="input" onchange="force2decimals(this)" value="1.00" />

I hope this was helpful.

Altay Akkus
  • 248
  • 1
  • 10
Shafiqul Islam
  • 5,065
  • 1
  • 26
  • 39
  • there is no jQuery tag for the question. That means he wants it by JavaScript. Not jQuery – Mojtaba Aug 16 '16 at 20:26
  • In this question, there is no restriction to use jQuery so why we do not use jQuery if it will easy and in this question there is no jQuery tag that ok but if question provider miss tag then we can not answer using related something? – Shafiqul Islam Aug 16 '16 at 20:59
  • @ShafiqulIslam Yes, that is the current protocol. If a user has not applied the jQuery tag, and you want to provide a jQuery solution, first ask in a comment if the OP is amenable to using jQuery. –  Aug 17 '16 at 03:20
  • @torazaburo ok i will do it . – Shafiqul Islam Aug 17 '16 at 06:21
  • @ShafiqulIslam, sometimes jQuery makes it easy. But, many developers prefer to use the native JS syntaxes and do not use jQuery. It depends on your project, expectations and limitations. So, when someone is using native JavaScript for his/her project, we should try to solve his/her problem on the way is under used. – Mojtaba Aug 17 '16 at 14:04
  • Yup, I didn't specify it in the question but I'm not looking for a jQuery solution. Thanks anyway! – Yann Bertrand Aug 18 '16 at 09:42