'How to "mask" an input to show brazilian currency
I need a input range shows the value formatted for Brazilian money. By logic, it would suffice to receive this number in a function that would format it and then return the formatted value. But this is Javascript, and I found no way to make it work.
function converter(valor){
var numero = (valor).toLocaleString('pt-BR');
document.getElementById('valor').value = 'R$ '+numero;
}
<input type="range" min="0" max="4000.00" value="2000.00" step="0.01" style="width:100%" oninput="converter(this.value)">
<p>
<input type="text" name="valor" value="R$ 0,00" id="valor">
Solution 1:[1]
You can use the second parameter of the toLocaleString()
that is the options
style argument, where you can set the currency, so you don't even need to use the concatenation with "R$"
because it will be ready when toLocaleString
is called.
Note that it's not current working for you because toLocaleString()
is part of the Number.prototype
in javascript and the parameter valor
that you have is a string, so it won't work if you don't parse the string to number.
See below.
function converter(valor){
var numero = parseFloat(valor).toLocaleString('pt-BR',{ style: 'currency', currency: 'BRL' });
document.getElementById('valor').value = numero;
}
<input type="range" min="0" max="4000.00" value="2000.00" step="0.01" style="width:100%" oninput="converter(this.value)">
<p>
<input type="text" name="valor" value="R$ 0,00" id="valor">
Further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
Solution 2:[2]
In case you are doing it with ReactJS I would suggest you to take a look in this component. You also could wrap it in a custom component e.g.component={TextField}
import React from "react"
import IntlCurrencyInput from "react-intl-currency-input"
const currencyConfig = {
locale: "pt-BR",
formats: {
number: {
BRL: {
style: "currency",
currency: "BRL",
minimumFractionDigits: 2,
maximumFractionDigits: 2,
},
},
},
};
const BrlCurrencyComponent = () => {
const handleChange = (event, value, maskedValue) => {
event.preventDefault();
console.log(value); // value without mask (ex: 1234.56)
console.log(maskedValue); // masked value (ex: R$1234,56)
};
return(
<IntlCurrencyInput
component={TextField}
currency="BRL"
config={currencyConfig}
onChange={handleChange}
/>
);
}
export default BrlCurrencyComponent;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |