skip to Main Content

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

Answers


  1. export const formatCurrencyNumberWithDecimal = (amount) => {
      var i = parseFloat(amount);
      if (isNaN(i)) {
        i = 0.0;
      }
      var minus = '';
    
      if (i < 0) {
        minus = '-';
      }
    
      i = Math.abs(i);
      i = parseInt((i + 0.005) * 100);
      i = i / 100;
      var s = new String(i);
    
      if (s.indexOf('.') < 0) {
        s += '.00';
      }
      if (s.indexOf('.') == s.length - 2) {
        s += '0';
      }
    
      return minus + s;
    };
    

    can you try this logic

    Login or Signup to reply.
  2. 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;
        }
    ...
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search