How to format currency with input in reactjs

661 Views Asked by At

I want to format currency as 1,456,567.545 and here is my code

export const formatCurrencyNumberWithDecimal = (value) => {
  if(value){
    const cleanedValue = value.replace(/,/g, ''); // Remove existing commas
    const parts = cleanedValue.split('.');
    const integerPart = parts[0].replace(/\D/g, ''); 
    const decimalPart = parts[1] ? parts[1].replace(/\D/g, '').slice(0, 4) : '';

    let formattedValue = '';

    if (integerPart) {
      formattedValue = parseFloat(integerPart).toLocaleString('en-US');
    }

    if (decimalPart) {
      formattedValue += `.${decimalPart}`;
    }

    console.log("formattedValue", formattedValue)

    return formattedValue;
  }
}

the function above to format input number.

and function below to handle onChange

const onChangeAverageUnitPrice = (e) => {
   setAverageUnitPrice(formatCurrencyNumberWithDecimal(e.target.value))
}

and the last is my input

 <InputField
    type="text"
    value={averageUnitPrice}
    onChange={onChangeAverageUnitPrice}
 />

my problem is when commenting the return line in the formatCurrencyNumberWithDecimal function and viewing the log output (consolo.log) then the result is as i expected enter image description here

But when I open the comment line return, I can't press "." . My expected is to be able to press decimal point "."

Can anyone give me some advice to resolve or is there any other way to do it? Thanks everyone

2

There are 2 best solutions below

2
On
export const formatCurrencyNumberWithDecimal = (amount) => {
  var p = amount.toFixed(2).split(".");

  return  p[0].split("").reverse().reduce(function(acc, amount, i, orig) {
    return amount + (amount != "-" && i && !(i % 3) ? "," : "") + acc;
}, "") + "." + p[1];
};

can you try this logic

0
On

I hope this code can work for you

export const formatCurrencyNumberWithDecimal = (value) => {
  if(value){
// user added dot at last input, just remain it
    if( averageUnitPrice + "." === value ) {
      return value;
    }
...
  }
}