Search code examples
javascriptreactjscurrency

Currency format in euro


I am working on a component which formats value to render in different formats such as Dollar and Euro with commas and dots. I have a working Dollar input however my Euro input does not work and input does not get correct values which i enter, i have tried different solutions but can not figure out the missing piece. This is the very minimized version of component and sandbox link. Thanks in advance.

Sandbox https://codesandbox.io/s/elated-sea-7328g?file=/src/App.js

import "./styles.css";
import {useState} from "react";
export default function App() {

  const [inputValue, setInputValue] = useState("");
  const [inputUsdValue, setinputUsdValue] = useState("");

  const currencyFunction = (formatData) => { 
    return  new Intl.NumberFormat('it-IT').format(formatData)
}

const currencyFunctionDolar = (formatData) => { 
  return  new Intl.NumberFormat('en-US').format(formatData)
}
  return (
    <div className="App" style={{display: "flex", flexFlow: "column"}}>
      <h1>Test component</h1>

      <p>Euro format</p>
      <p>Euro format example {currencyFunction(123456789)}</p>
      <input 
        value={currencyFunction(inputValue)}
        onChange={e => {
                  setInputValue(e.target.value.replace(/,/g, '.').replace(/([a-zA-Z ])/g, ""))
        }} 

        style={{marginBottom: 20}}
    />
    <p>Usd format</p>
    <p>Usd format example {currencyFunctionDolar(123456789)}</p>
    <input 
        value={currencyFunctionDolar(inputUsdValue)}
        onChange={e => {
                  setinputUsdValue(e.target.value.replace(/,/g, '').replace(/([a-zA-Z ])/g, "").replace(/^0+/, ''))
        }} 
    />
    </div>
  );
}

Solution

  • For your onChange event on the euro currency, you want to remove the . the same way you are removing the , for the dollars, and you can achieve that as follow:

    setInputValue(e.target.value.replace(/[.]/g, '').replace(/([a-zA-Z ])/g, "").replace(/^0+/, ''))
    

    The reason for enclosing the . in brackets ([]) is because it is a special character in regular expressions.

    Working sandbox example: https://codesandbox.io/s/ecstatic-wilson-or7qd?file=/src/App.js