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
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
can you try this logic