react-native-amount-textfield
Version:
This library gives you a Amount TextField component, which has formatted value based on International Currency standard. The component return back float value ( the actual Number) and a Formatted value which can be saved in a state and used for display i
55 lines • 2.64 kB
JavaScript
import React from 'react';
import { TextInput } from 'react-native';
// const regex = /^-?[0-9]*\.?[0-9]+$/gm
const numberWithCommas = (x) => {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};
export const getFormattedFloatNumber = (value, precision) => {
const valueString = value.toString();
const valueSplit = valueString.split('.');
const decimalPortion = valueSplit[1];
const backNumber = decimalPortion === undefined
? `${'0'.repeat(precision)}`
: decimalPortion.length < precision
? `${decimalPortion}${'0'.repeat(precision - decimalPortion.length)}`
: decimalPortion;
const frontNumberString = valueSplit[0];
const frontNumber = numberWithCommas(frontNumberString);
return `${frontNumber}.${backNumber}`;
};
export const AmountTextField = ({ precision = 2, value, onChangeValue, ...props }) => {
const formatAndCallback = (formattedValue, error, decimalLength) => {
const updatedString = formattedValue.replace(/,/g, '');
const floatValue = error
? `${updatedString}00`
: decimalLength === 1
? `${updatedString}0`
: updatedString;
onChangeValue === null || onChangeValue === void 0 ? void 0 : onChangeValue({
formattedValue,
floatValue: parseFloat(floatValue),
error,
});
};
return (React.createElement(React.Fragment, null,
React.createElement(TextInput, { value: value, placeholder: 'Enter Amount', keyboardType: 'decimal-pad', onChangeText: (newValue) => {
const updatedString = newValue.replace(/,/g, '');
const valueSplit = updatedString.split('.');
const decimalPortion = valueSplit[1];
const frontNumberString = valueSplit[0];
const frontNumber = numberWithCommas(frontNumberString);
if (decimalPortion && decimalPortion.length <= precision) {
const newFormattedNumber = `${frontNumber}.${decimalPortion}`;
formatAndCallback(newFormattedNumber, false, decimalPortion.length);
}
if (decimalPortion === undefined) {
const newFormattedNumber = `${frontNumber}`;
formatAndCallback(newFormattedNumber, false, 0);
}
if (decimalPortion === '') {
const newFormattedNumber = `${frontNumber}.`;
formatAndCallback(newFormattedNumber, true, 0);
}
}, ...props })));
};
//# sourceMappingURL=index.js.map