As Tom said in the comment above, you'll want to set myValue in state to the value returned by passing your value through the format function:
function currencyFormat(num) {
return parseFloat(num).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}
handleChange = (e) => {
setValue(currencyFormat(e.target.value))
}
Right now you're initializing myValue as a number, but your currencyFormat function returns a string. For good practice, you'll probably want to initialize your value as a string that matches the format you want your currencyFormat to return.
Even if you do that, though, your currencyFormat won't work as expected. Once you've changed the value, myValue will be set to the formatted string, which will include a comma if the value is >= 1000. Since parseFloat ignores everything after any character that isn't "+" or "-" or ".", if your value already includes a comma, parseFloat will return the wrong value:
function currencyFormat(num) {
return parseFloat(num).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}
console.log(currencyFormat("12,345.6"))
// => "12.00"
What you probably want to do is keep your value saved as the string representation, and remove all non-numeric characters from your input value before parsing and formatting:
function currencyFormat(num) {
return parseFloat(num.replace(/[^0-9.]/g, ""))
.toFixed(2)
.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}
console.log(currencyFormat("12,345.6"))
// => "12,345.60"
Play around with this sandbox to see how your currency format behaves (try giving it a number >= 10,000) and how this updated version behaves.
(Alternatively, you could use a masked input component, and keep myValue as a float rounded to 2 decimal places, but that would be a bigger change.)