Function that transforms value of an input


I have an input that collects the value of height, and a function that transforms the value:

  • case 1: if income 123 adds a zero (0) and the result is 123.0 THIS GOOD
  • case 2: if you enter 123.4, leave it as is. IT'S GOOD
    case 3: if income 99 adds a zero (0) and the result is 123.0 THIS GOOD
  • case 4: if I enter 1.23 I will transform it to 123.0 THIS GOOD
  • But in case 5: if I enter 99.4 he transforms it to 994.00. THAT'S WRONG. I should leave it equal 99.4.


function format(input){
	var num = input.value.replace(/\./g,'');
    console.log(parseFloat(Math.round(num * 100) / 100).toFixed(1));
<input type="text" id="ejemplo" name="ejemplo"/>
<button type="button"  onclick="format(ejemplo)">Prueba</button>
asked by Carla Noguera 10.11.2017 в 17:20

1 answer


It seems that what you want is to calculate the height in centimeters with a decimal, although you allow the user to enter the amount in centimeters or in meters.

A possible solution would be to check if the value entered is less than 3 and multiply by 100 in those cases (because the data entered will have been in meters). From that, you would perform the operations you want, which is really none ... because toFixed will do the rounding for you, so the Math.round is unnecessary.

function format(input) {

  // leemos el numero
  var num = parseFloat(input.value);
  // si esta en metros lo pasamos a centimetros
  if (num < 3) {
    num = num * 100;

  // mostramos el resultado en centimetros
<input type="text" id="ejemplo" name="ejemplo" />
<button type="button" onclick="format(ejemplo)">Prueba</button>
answered by 10.11.2017 / 18:04