Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

javascript - 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. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

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:

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.'). 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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...