Skip to content

Commit

Permalink
Merge pull request baidu#8799 from allenve/master
Browse files Browse the repository at this point in the history
fix(amis):input-number 小数光标偏移问题
  • Loading branch information
allenve authored Nov 17, 2023
2 parents a37bd5b + cccca16 commit 71c7b72
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 6 deletions.
2 changes: 2 additions & 0 deletions packages/amis-core/__tests__/utils/math.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
12 changes: 8 additions & 4 deletions packages/amis-core/src/utils/math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
Expand Down
5 changes: 3 additions & 2 deletions packages/amis/src/renderers/Form/InputNumber.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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);
}
}
Expand Down

0 comments on commit 71c7b72

Please sign in to comment.