簡體   English   中英

在Vue中使用千位分隔符格式化數字

[英]Format number with the thousand separator in Vue

我有除法計算器,它的工作很清楚,但我對計算結果不滿意。當你看到下面的 SS 時,你會更好地理解。我想要的是刪除不必要的零,在必要的地方放逗號,如果結果顯示更容易理解的數字顯示數字千。 例如:不是19350.00 ,這應該是19,350

結果

在此處輸入圖像描述

我想要的是

在此處輸入圖像描述

模板

  <input
    type="text"
    class="form-control h-35"
    autocomplete="off"
    v-model="purchasePrice"
  />
  <input
    type="text"
    class="form-control h-35"
    autocomplete="off"
    v-model="salePrice"
  />

  <p>{{ marginResult }}</p>

腳本

data() {
    return {
      purchasePrice: null,
      salePrice: null,
      marginPrice: null,
    };
  },
  computed: {
    marginResult() {
      const res = parseFloat(
        ((this.salePrice - this.purchasePrice) / this.salePrice) * 100
      ).toFixed(2);
      if (isNaN(res) || res == "-Infinity") {
        return "";
      }
      return res;
    },
  },

只需使用Intl.NumberFormat實用程序 object 來格式化數字:

...
return new Intl.NumberFormat('en-US').format(res);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM