Skip to content

Instantly share code, notes, and snippets.

@SPavelV
Last active October 25, 2019 15:39
Show Gist options
  • Select an option

  • Save SPavelV/b844bdeeb87bd2879980b9adc047b815 to your computer and use it in GitHub Desktop.

Select an option

Save SPavelV/b844bdeeb87bd2879980b9adc047b815 to your computer and use it in GitHub Desktop.
Currency input formatted
formattedValue = (value: string | undefined) => {
if (value) {
const thousandSepartor = this.props.thousandSeparаtor ? this.props.thousandSeparаtor : " ";
const currencySymbol = this.props.currencySymbol ? this.props.currencySymbol : "";
const regexSeparator = new RegExp("\\" + this.props.decimalSeparator);
const regexFloat = new RegExp("[^" + this.props.decimalSeparator + "]?\\d?\\d?$");
let floatValue = "00";
let matchStart = -1;
if (regexSeparator.test(value)) {
// сохраняем дробное значение
const matchFloat = regexFloat.exec(value);
if (matchFloat && matchFloat.length > 0) {
matchStart = matchFloat.index || -1;
floatValue = matchFloat[0];
floatValue = floatValue.length === 0 ? "00" : floatValue.length === 1 ? `${floatValue[0]}0` : `${floatValue}`;
}
// сокращаяем value до дробного значения
value = value.slice(0, --matchStart);
}
// добавляем разделитель тысяч и символ валюты
let newValue = value.replace(/\s+/g, "").match(/(\d{1,3})(?=((\d{3})*([^\d]|$)))/g);
if (newValue) {
return newValue.join(thousandSepartor) + `${this.props.decimalSeparator}${floatValue} ${currencySymbol}`;
} else return "";
} else {
return <span className="input-money-placeholder">{this.props.placeholder}</span>;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment