Search code examples
javascripthtmljquerynumber-formattingunits-of-measurement

Conditionally format number decimals after converting them to centimetres or inches


I have a toggle that converts my numbers to centimetres or inches with 1 decimal.

However, I would like centimetres to have no decimals, while inches have 1 decimal place.

This is my current code:

function converTo(scale) {
  $('#ct_size_guide-1761 td').each(() => {
   // I forgot exact conversion:
    var multiplier = (scale == 'in') ? 2.5 : 0.4; 
    var newVal=(parseFloat($(this).text()) * multiplier).toFixed(1);   

    $(this).text(newVal);
    $(this).siblings('.scale').text((scale=='in')? 'cm' : 'in') ;
  });
}

Solution

  • You just need to conditionally format the numbers, the same way you use different values for multiplier depending on the selected unit.

    So you need to replace:

    var multiplier = scale === 'in' ? 2.5 : 0.4;
    var newVal = (parseFloat($(this).text()) * multiplier).toFixed(1); 
    

    With something like:

    var newVal = scale === 'in'
      ? (parseFloat($(this).text()) * 2.5).toFixed(1)
      : (parseFloat($(this).text()) * 0.4).toFixed(0); 
    

    This way you can have different multipliers but also different formatting for each unit.

    I would probably restructure the code with an if-else rather than a ternary. This way it will be easier to implement different behaviours (conversion, formatting...) depending on the selected unit:

    const $value = $('#value');
    const $unit = $('#unit');
    const $result = $('#result');
    
    function updateConverstion() {
      const value = parseFloat($value.val());
      const unit = $unit.val();
      
      let targetValue;
      let targetUnit;
      
      if (unit === 'in') {
        // Show centimeters without decimals:
        targetValue = Math.round(value * 2.54);
        targetUnit = 'cm';
      } else {
        // Show inches with 1 decimal:
        targetValue = (value * 0.393701).toFixed(1);
        targetUnit = 'in';
      }
    
      $result.text(`${ value } ${ unit } = ${ targetValue } ${ targetUnit }`);
    }
    
    $value.on('input', updateConverstion);
    $unit.on('change', updateConverstion);
    
    updateConverstion();
    <input type="text" value="100" id="value" />
    
    <select id="unit">
      <option value="cm" selected>Centimeters</option>
      <option value="in">Inches</option>
    </select>
    
    <p id="result"></p>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>