我尝试使用numeraljs和纯javascript来格式化输入字段中的货币输入值,但它一直在删除小数。我想不出该怎么解决这个问题。下面是我的代码
<input v-model="amountValue"></input>`<script>
import import numeral from 'numeral';
data: function() {
return {
formData:{
amount: "",
},
};
},
computed:{
amountValue: {
get(){
return this.formData.amount
},
set(value){
this.formData.amount = numeral(value).format('0,0[.]00')
console.log(this.formData.amount)
}
}
},
// I have also tried without numeraljs
computed:{
amountValue: {
get(){
return this.formData.amount
},
set(value){
this.formData.amount = parseInt(value).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
console.log(this.formData.amount)
}
}
},它适用于千位分隔符,但小数不会保留。
当我开始输入时,它会格式化输入值(带有千位分隔符),但当我输入小数时,它会将其删除。
发布于 2021-01-07 03:45:12
我已经尝试运行您的第一个示例。它像预期的那样工作,但可能看起来很奇怪:
我将输入金额1000.1,这是发生的情况:
type 1 - display 1
type 10 - display 10
type 100 - display 100
type 1000 - display 1,000
type 1000. - display 1,000 (odd)
type 1000.1 - display 1,000.10现在,当我想输入一个不同的数字时,比如5.012,它就变得更奇怪了:
type 5 - display 5
type 5. - display 5 (odd)
type 5.0 - display 5 (odd)
type 5.01 - display 5.01
type 5.012 - display 5.01 (slightly odd)因为您在每次击键时都要格式化,所以您会遇到输入不是有效数字的状态(例如,当我键入‘1000.’时)。您可能需要决定如何处理这些无效状态。
为了验证您的代码是否工作正常,我测试的代码将包含以下jsfiddle:https://jsfiddle.net/jangnoe/0718q6e4/
https://stackoverflow.com/questions/65601937
复制相似问题