Search code examples
javascripthtmldecimalcalculationinput-field

Decimal / Thousand separator (dot and comma) in the calculation results Js and Input field


I'm trying to get separators for thousands, hundreds and decimals in the input field. For example: if I calculate 50 * 50 the result is 2500 while I would like to get 2.500,00

Otherwise: if I calculate 52,5 * 52,5 the result is 2756.25, while I would like to get 2.756,25

Below is the code I worked out helping me with stackoverflow posts https://jsfiddle.net/snake93/dyepq135/10/

I'm a fan and don't even know the basics of coding, so I was just trying to figure out how to implement the separators (dot and comma).

<label class="mts-label">Peso</label>
<input  type="number" step="any" class="mts-field" maxlength="4" id="peso" name"peso1" placeholder="es: 70Kg"/>

<label class="mts-label">Altezza</label>
<input  type="number" class="mts-field" maxlength="4" id="altezza" name"altezza1" placeholder="es: 170cm"/>

<label class="mts-label">BMR</label>
<input  type="text" class="mts-field" id="bmruomo" name="bmruomo"
placeholder="0.000,0 Kcal" min="1" readonly/>

<button onclick="calculate()">Calcola</button>
<button id="reset" onclick="resetFields()">Reset</button>
calculate = function() {
 var peso = document.getElementById('peso').value;
 var altezza = document.getElementById('altezza').value;
 var bmruomo = parseFloat(peso * altezza);
  document.getElementById('bmruomo').value = bmruomo;

}
   
function resetFields(){
 var inputArray = document.querySelectorAll('input');
  inputArray.forEach(function (input){
    input.value = "";
    });
}

Solution

  • You can do that...

    const
      f_BMR = document.forms['f-BMR']
    , num2strEUR = n =>
      {
      let str = n.toFixed(2).replace('.',',')
      return [...str].reduce((r,c,i,a)=>
        {
        r += c
        let p = (a.length - i) 
        if ((p%3)===1 && p>4) r += '.'
        return r 
        },'')
      }
    f_BMR.onsubmit = e =>
      {
      e.preventDefault()
      let bmr_val = (f_BMR.peso1.valueAsNumber * f_BMR.altezza1.valueAsNumber) 
    
      f_BMR.bmruomo.value = num2strEUR(bmr_val )
      }
    label,input, div {
      display    : block;
      float      : left;
      clear      : both;
      }
    label, div{
      font-size   : .7em;
      font-weight : bold;
      margin-top  : .8em;
      }
    label:after {
      content     : ' :'
      }
    <form name="f-BMR">
      <label>Peso</label>
      <input name="peso1" type="number" step="any" placeholder="es: 70Kg" value="" required>
    
      <label>Altezza</label>
      <input name="altezza1" type="number" step="any" placeholder="es: 170cm"/ value="" required>
    
      <label>BMR</label>
      <input name="bmruomo" type="text" class="mts-field" placeholder="0.000,0 Kcal" value="" readonly>
    
      <div>
        <button type="submit">Calcola</button>
        <button type="reset">Reset</button>
      </div>
    </form>