Open Nidhi-Vedaha opened 2 years ago
related to #43 and #39
This works with MUI 5, and was my solution. Not as many features as the actual plugin, but largely accomplishes the same thing.
Info on toLocaleString can be found here. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
const setPrice = (e) => {
setPrice(e.target.value.replace(/[^0-9\.]/gi, ""));
};
const convertPrice = () => {
let tempPrice = Number(price).toLocaleString("en-EN", {
style: "currency",
currency: "USD",
});
setPrice(tempPrice);
};
<TextField
value={price}
onChange={setPrice}
onBlur={convertPrice} />
This works with MUI 5, and was my solution. Not as many features as the actual plugin, but largely accomplishes the same thing.
Info on toLocaleString can be found here. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
const setPrice = (e) => { setPrice(e.target.value.replace(/[^0-9\.]/gi, "")); }; const convertPrice = () => { let tempPrice = Number(price).toLocaleString("en-EN", { style: "currency", currency: "USD", }); setPrice(tempPrice); };
<TextField value={price} onChange={setPrice} onBlur={convertPrice} />
Thank you for this. I would suggest adding the following though. First issue is this solution allows a user to enter multiple periods (eg: 50000.12.4141.1212) which will result in NaN when passed to Intl.toLocaleString. Simply test if there is more than one period, split the string by periods, and only return the first 2 results (dollars, cents) to make a clean string.
if (tempPrice.match(/\./g).length > 1) {
const [dollars, cents] = tempPrice.split('.')
tempPrice = `${dollars}.${cents}`
}
Next the solution will always return the string with a leading $. Since you probably don't want this in your data, you can strip it with
tempPrice = tempPrice.replace(/\$/g, '')
Putting it all together with the original solution, your onBlur will look like:
const convertPrice = () => {
let tempPrice = price
if (tempPrice.match(/\./g).length > 1) {
const [dollars, cents] = tempPrice.split('.')
tempPrice = `${dollars}.${cents}`
}
tempPrice = Number(tempPrice).toLocaleString('en-EN', {
style: 'currency',
currency: 'USD',
})
tempPrice = tempPrice.replace(/\$/g, '')
setPrice(tempPrice)
}
We're all waiting for @merlos or @sureshsevarthi to merge pull request #43 to update it to be compatible with MUI v5