Skip to content

Commit 7a44614

Browse files
committed
[Fix] Reverse fill issue when input fraction digit less than precision
1 parent bf31462 commit 7a44614

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

docs/.vuepress/components/PlayGround.vue

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,8 @@ export default {
140140
return {
141141
updated: true,
142142
exportDialogVisible: false,
143-
price: 1234.567,
144-
priceDirective: 1234.567,
143+
price: 1234.50,
144+
priceDirective: 1234.50,
145145
config: {
146146
decimal: '.',
147147
separator: ',',

src/number-format.ts

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,6 @@ function fixed(precision: number) {
2424
return between(0, precision, 20)
2525
}
2626

27-
function toFixed(numbers: string, precision: number) {
28-
const exp = Math.pow(10, precision)
29-
const float = parseFloat(numbers) / exp || 0
30-
return float.toFixed(fixed(precision))
31-
}
32-
3327
/**
3428
* Number format class
3529
* @param {Options} config
@@ -82,12 +76,26 @@ export default class NumberFormat {
8276
return hasMinus ? '-' : ''
8377
}
8478

79+
toFixed() {
80+
const padEnd = (num: string) => {
81+
const parts = num.split(this.options.decimal)
82+
parts[1] = parts[1].padEnd(this.options.precision, '0')
83+
return parts.join('')
84+
}
85+
const exp = Math.pow(10, this.options.precision)
86+
const float = parseFloat(padEnd(this.numberOnly())) / exp || 0
87+
return float.toFixed(fixed(this.options.precision))
88+
}
89+
8590
toNumber(str: Input) {
8691
return Number(str)
8792
}
8893

89-
numberOnly(str: Input, regExp: RegExp) {
90-
return str?.toString().replace(regExp, '')
94+
numberOnly(str?: Input, regExp?: RegExp) {
95+
return (str || this.input)
96+
?.toString()
97+
.replace(this.preSurRegExp, '')
98+
.replace(regExp || this.numberRegExp, '')
9199
}
92100

93101
isNegative() {
@@ -96,13 +104,11 @@ export default class NumberFormat {
96104

97105
numbers() {
98106
if (this.options.reverseFill) {
99-
this.number = toFixed(this.numberOnly(this.input, /\D+/g), this.options.precision).replace('.', this.options.decimal)
107+
this.number = this.toFixed().replace('.', this.options.decimal)
100108
} else if (typeof this.input === 'number') {
101109
this.number = this.parts(this.input.toString().replace('-', ''), '.').join(this.options.decimal)
102110
} else {
103-
const input = this.input.replace(this.preSurRegExp, '')
104-
this.number = this.numberOnly(input, this.numberRegExp)
105-
this.number = this.parts(this.number).join(this.options.decimal)
111+
this.number = this.parts(this.numberOnly()).join(this.options.decimal)
106112
}
107113
return this.number
108114
}

0 commit comments

Comments
 (0)