-1

I have a normal HTML text input that will contain currency values calculated from other values and rounded to 2 decimal places

<input type="text" class="form-control" id="prevloans" name="prevloans" readonly='readonly'>

The issue is that if the value is something like 23.30, it will only show it as 23.3. How do I make sure two digits are always shown without using input type="number"?

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Monty Swanson
  • 695
  • 16
  • 41
  • How are you setting the value? Most likely you are setting it as a number, which gets auto-cast to a string - you want to manually cast to string with a trailing 0. – Luke Storry Sep 22 '20 at 11:29
  • @LukeStorry like this : $('#' + pid + '8').text((sum.toFixed(2))); – Monty Swanson Sep 22 '20 at 11:31
  • var number = 12132.2343243 var rounded = Math.round(number * 10) / 10 , it will return `12132.2` – KALITA Sep 22 '20 at 11:37

4 Answers4

0

I can see that the field is a "readonly" type. Which means that you can't use input event listener for that. However, what you can do it call a function wherever you place the value inside the field. It is pure javascript, independent of jQuery.

function setValue(val){
  let field = document.querySelector("#prevloans");
  field.value = Number(val).toFixed(2)
}
Pranav Rustagi
  • 2,604
  • 1
  • 5
  • 18
0

You can do this with HTML and a little bit of Javascript.

Since you don't want to use number type on input, then use a pattern to match the format that you want, in this case x.xx. So a pattern like this one [\d]+([\.][\d]{2}) would apply.

var inpObj = document.getElementById("myinp");
inpObj.addEventListener('input', () => {
  if (!inpObj.checkValidity()) {
    console.log(inpObj.validationMessage);
  } else {
    console.log('you typed: ' + inpObj.value);
  }
});
<input type="text" id="myinp" name="myinp" pattern="[\d]+([\.][\d]{2})">

Since this is a readonly input, pattern will not help, then 2-3 simple lines of JS can help.

function myFunction() {
let inp = document.querySelector('#myinp')
inp.value = parseFloat(inp.value).toFixed(2);
}
<body onload="myFunction()">
<input type="text" id="myinp" name="myinp" value="23.3" readonly="readonly">
</body>
-1

Try this. Casts it to a float and then a string. It should apply changes in real time as the user types.

$('#prevloans').on('input', function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});
Rohan B
  • 86
  • 8
-2

Note: You need to use up and down arrows (after inserting numbers):

Try this:

<input type="number" class="form-control" id="prevloans" name="prevloans" step="0.01" >

Also, checkout: https://www.xspdf.com/resolution/50892510.html#:~:text=Allow%202%20decimal%20places%20in,form%20is%20submit%2C%20not%20onblur.

Deadpool
  • 7,811
  • 9
  • 44
  • 88