简体   繁体   English

在 vue 中格式化货币值

[英]Formatting currency value in vue

I am trying to format currency entered value in input field using numeraljs and plain javascript but it keeps deleting the decimal.我正在尝试使用 numericjs 和普通的 javascript 在输入字段中格式化货币输入值,但它一直在删除小数点。 Can not figure out how to fix this.无法弄清楚如何解决这个问题。 My code below我的代码如下

<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)
      }
     

    }
  },

It works with the thousand separator but the decimal wont stay.它适用于千位分隔符,但小数点不会保留。

When I start typing, it formats the input value(with thousand separator) but when I type in a decimal, it deletes it.当我开始输入时,它会格式化输入值(带有千位分隔符),但是当我输入小数时,它会删除它。

I have tried to run your first example.我试图运行你的第一个例子。 It works as expected but it may seem odd:它按预期工作,但可能看起来很奇怪:

I'm going to type the amount 1000.1, this is what happens:我要输入金额 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

Now when i want to type a different number, like 5.012 it becomes weirder:现在当我想输入一个不同的数字时,比如 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)

Because you are formatting on each keystroke you will encounter states in which the input is not a valid number (for instance when I types '1000.').因为您在每次击键时都在格式化,所以您会遇到输入不是有效数字的状态(例如,当我键入“1000.”时)。 You may want to decide how to deal with these invalid states.您可能想决定如何处理这些无效状态。

To verify if your code works the same is the code I tested with i'll include this jsfiddle: https://jsfiddle.net/jangnoe/0718q6e4/为了验证您的代码是否相同,我测试的代码将包含这个 jsfiddle: https://jsfiddle.net/jangnoe/0718q6e4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM