skip to Main Content

I have a question trying to have the input field auto-add a comma on input for readability. E.g 123,456.

.toLocaleString() has been used to resolve the end result, but i need the comma displaying at the time of input also.

Thanks.

  const handleGrossIncomeChange = (event) => {
    const { name, value } = event.target;
    setGrossIncome(value);
    if (resultShower === false){
    setResultShower(!resultShower);
    resultExport = resultShower;
    }
    else {
      return resultShower
    }
  
  };

 <div className="inputClass">
      <div className="input-group">
        <p>Gross Income {""}
          <span className="currency-input">
            <span className="currency-symbol">£</span>
            <input
              type="number"
              name="grossIncome"
              id="grossIncome"
              autoComplete="off"
              onChange={handleGrossIncomeChange}
              className="currency-value"
              placeholder="0.00"
            />
          </span>
        </p>

      </div>


<button type="submit" name="resultTester" onClick={handleClick}>click me </button>

2

Answers


  1. You can use Intl.NumberFormat Api like below:

    function formatCurrency(event) {
    
      let value = event.target.value;
      
    
      value = value.replace(/[^d]/g, '');
      
    
      value = new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(value / 100);
      
      event.target.value = value;
    }
    <input type="text" id="amount" oninput="formatCurrency(event)">
    Login or Signup to reply.
  2. Since the input value contains "," (not a number), the input has to be of the text type.

      <input
        type="text"
        onChange={(e) => {
          const value = parseInt(e.currentTarget.value.replaceAll(",", ""));
          if (isNaN(value)) e.currentTarget.value = "0";
          else e.currentTarget.value = value.toLocaleString();
          setGrossIncome(value);
        }}
      />
    

    (Tested in React v18.0, ES5)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search