Last active
October 25, 2019 15:39
-
-
Save SPavelV/b844bdeeb87bd2879980b9adc047b815 to your computer and use it in GitHub Desktop.
Currency input formatted
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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