Home > Software engineering >  Currency format in euro
Currency format in euro

Time:10-22

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>
  );
}

CodePudding user response:

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

CodePudding user response:

Intl.NumberFormat takes not only the locale, but also an options object defining the style and currency (see the docs for more information). In your case, you'll probably want something like this instead for the Euros in Italy:

const currencyFunction = (formatData) => {
  return new Intl.NumberFormat('it-IT', {
    style: 'currency',
    currency: 'EUR',
  }).format(formatData)
}

currencyFunction(123456789) // Will output '123.456.789,00 €'

And for the dollars in the USA:

const currencyFunctionDollar = (formatData) => {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
  }).format(formatData)
}

currencyFunctionDollar(123456789) // Will output '$123,456,789.00'
  • Related