fix(amis):input-number 小数光标偏移问题

This commit is contained in:
allenve 2023-11-17 15:56:41 +08:00
parent 1d6f55aabc
commit cccca16e25
3 changed files with 13 additions and 6 deletions

View File

@ -16,6 +16,8 @@ test(`math safeSub:test`, () => {
test('numberFormatter:test', () => {
expect(numberFormatter(0)).toEqual('0');
expect(numberFormatter(0.123)).toEqual('0.123');
expect(numberFormatter(0.123, 0)).toEqual('0');
expect(numberFormatter(0, 2)).toEqual('0.00');
expect(numberFormatter(0, 8)).toEqual('0.00000000');
expect(numberFormatter(123456)).toEqual('123,456');

View File

@ -31,14 +31,18 @@ export function safeSub(arg1: number, arg2: number) {
return (arg1 * maxDigits - arg2 * maxDigits) / maxDigits;
}
export function numberFormatter(num: number | string, precision: number = 0) {
export function numberFormatter(num: number | string, precision?: number) {
const ZERO = 0;
const number = +num;
const finalP =
typeof precision === 'number'
? precision
: number.toString().split('.')[1]?.length || 0;
if (typeof number === 'number' && !isNaN(number)) {
const regexp = precision ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(\d{3})+$)/g;
return number.toFixed(precision).replace(regexp, '$1,');
const regexp = finalP ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(\d{3})+$)/g;
return number.toFixed(finalP).replace(regexp, '$1,');
}
return ZERO.toFixed(precision);
return ZERO.toFixed(finalP);
}
/**

View File

@ -330,6 +330,7 @@ export default class NumberControl extends React.Component<
return;
}
const {kilobitSeparator, prefix} = this.props;
const integer = value > 0 ? Math.floor(value) : Math.ceil(value);
let pos = `${value}`.length;
if (prefix) {
@ -338,13 +339,13 @@ export default class NumberControl extends React.Component<
if (kilobitSeparator) {
// 处理有千分符的情况 123,456,789
const ksLen = Math.floor((`${Math.abs(value)}`.length - 1) / 3);
const ksLen = Math.floor((`${Math.abs(integer)}`.length - 1) / 3);
if (ksLen > 0) {
pos += ksLen;
}
}
if (this.input) {
if (this.input && (kilobitSeparator || prefix)) {
this.input.setSelectionRange?.(pos, pos);
}
}