[英]regex InputNumber formatter ant-design
Guys I really not understand about regex, I'm using ant-design Input Number component to make a currency filter.伙计们,我真的不了解正则表达式,我正在使用 ant-design 输入数字组件来制作货币过滤器。
currently this is like this:目前是这样的:
<InputNumber
style={{ width: 175 }}
formatter={value => `R$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g,
".")}
parser={value => value.replace(/[A-Z]|[a-z]|[$ ]|\.+/g, "")}
onChange={(value) => setSelectedKeys(value ? value : [])}
/>
The current format, for exemple thousand five hundred is like this: 1.500 I need it to accept as well, negatives numbers (-1.500) and comma for the cents like 1.500,25当前的格式,例如千五百是这样的:1.500 我也需要它接受,负数(-1.500)和美分的逗号,如 1.500,25
Can you guys help me?你们能帮帮我吗? I've try some solutions but can't make it work as I need
我尝试了一些解决方案,但无法按我的需要工作
Guys after searching a lot,I found one solution, can't be the better one, but at moment is doing its job..伙计们经过大量搜索,我找到了一种解决方案,不可能是更好的解决方案,但目前正在做它的工作..
I installed MaskedInput and text-mask-addons dependencies.我安装了 MaskedInput 和 text-mask-addons 依赖项。
import MaskedInput from "react-text-mask";
import createNumberMask from "text-mask-addons/dist/createNumberMask";
const defaultMaskOptions = {
prefix: "R$",
suffix: "",
includeThousandsSeparator: true,
thousandsSeparatorSymbol: ".",
allowDecimal: true,
decimalSymbol: ",",
decimalLimit: 2,
integerLimit: 7,
allowNegative: true,
allowLeadingZeroes: false,
};
const currencyMask = createNumberMask(defaultMaskOptions);
const NumberFilter = (
<Space style={{ marginRight: 20 }}>
<MaskedInput
mask={currencyMask}
render={(ref, props) => (
<Input
placeholder="Valor inicial"
ref={(input) => ref(input && input.input)}
{...props}
value={selectedKeys[0]}
onChange={(event) => {
props.onChange(event);
let betweenInitial = [...selectedKeys];
betweenInitial[0] = event.target.value;
setSelectedKeys(betweenInitial);
}}
/>
)}
/>
<RiArrowLeftRightLine />
<MaskedInput
mask={currencyMask}
render={(ref, props) => (
<Input
placeholder="Valor final"
ref={(input) => ref(input && input.input)}
{...props}
value={selectedKeys[1]}
onChange={(event) => {
props.onChange(event);
let betweenFinal = [...selectedKeys];
betweenFinal[1] = event.target.value;
setSelectedKeys(betweenFinal);
}}
/>
)}
/>
</Space>
);
My solution:我的解决方案:
// formatter and parser input number
export const formatterNumber = (val) => {
if (!val) return 0;
return `${val}`.replace(/\B(?=(\d{3})+(?!\d))/g, ".").replace(/\.(?=\d{0,2}$)/g, ",");
}
export const parserNumber = (val) => {
if (!val) return 0;
return Number.parseFloat(val.replace(/\$\s?|(\.*)/g, "").replace(/(\,{1})/g, ".")).toFixed(2)
}
<InputNumber
{...props}
formatter={(value) => formatNumber(value)}
parser={(value) => parserNumber(value)}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.