Home > database >  Display INR number only if it's a number with more than 3 digits
Display INR number only if it's a number with more than 3 digits

Time:05-17

JSFiddle DEMO: https://jsfiddle.net/bukh7jwL/

I have a table with text & numbers and facing 2 problems.

  1. It disables all the text values and displays it as ₹NaN!!
  2. I would like to avoid applying the JS if the number has less than 100 as value or 3 digits.

How do I go about doing this?

HTML:

<center>
    <p>
      <table>
        <tr><td>This is amazing</td></tr>
        <tr><td>92834</td></tr>
        <tr><td>33</td></tr>
        <tr><td>What?</td></tr>
      </table>
</center>

JS:

$('td').each(function() {
  var monetary_value = $(this).text();
  var i = new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR'
  }).format(monetary_value);
  $(this).text(i);
});

CodePudding user response:

I've added the following statement to your code to check if we want to run the NumberFormat.

$.isNumeric(monetary_value) && (monetary_value < 100 || monetary_value.length == 3)

$.isNumeric(monetary_value) checks if it's a number.

(monetary_value < 100 || monetary_value.length == 3) checks if the value is below 100 or the length is 3 characters long.

$('td').each(function() {
  var monetary_value = $(this).text();
  if ($.isNumeric(monetary_value) && (monetary_value < 100 || monetary_value.length == 3)) {
    var i = new Intl.NumberFormat('en-IN', {
      style: 'currency',
      currency: 'INR'
    }).format(monetary_value);
  }
  $(this).text(i);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<center>
    <p>
      <table>
        <tr><td>This is amazing</td></tr>
        <tr><td>92834</td></tr>
        <tr><td>33</td></tr>
        <tr><td>What?</td></tr>
      </table>
</center>

CodePudding user response:

You have to first check if the string is a number or not after that you need to check if the number digits are 3 or more. After that using toLocaleString() the number will be converted into INR currency

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

$('td').each(function() {
  var monetary_value = $(this).text();
  if(isNumeric(monetary_value)) {
    let moneyVal = parseFloat(monetary_value);
    if( (moneyVal < 100 || moneyVal.toString().length == 3) ){
    var i = moneyVal.toLocaleString('en-IN', {
    maximumFractionDigits: 2,
    style: 'currency',
    currency: 'INR'
});
    $(this).text(i);
    
    }
  }
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<center>
    <p>
      <table>
        <tr><td>This is amazing</td></tr>
        <tr><td>92834</td></tr>
        <tr><td>33</td></tr>
        <tr><td>What?</td></tr>
      </table>
</center>

  • Related