Vue 구성 요소에서 통화를 포맷하려면 어떻게 해야 하는가?
내 Vue 구성 요소는 다음과 같다.
<template>
<div>
<div class="panel-group"v-for="item in list">
<div class="col-md-8">
<small>
Total: <b>{{ item.total }}</b>
</small>
</div>
</div>
</div>
</template>
<script>
export default {
...
computed: {
list: function() {
return this.$store.state.transaction.list
},
...
}
}
</script>
의 결과{{ item.total }}
이다
26000000
하지만 나는 이것을 이렇게 포맷하고 싶다.
26.000.000,00
jquery나 javascript로 할 수 있다.
그러나 vue 구성 요소에서는 어떻게 하는가?
나는 필터를 만들었다.필터는 어느 페이지에서나 사용할 수 있다.
Vue.filter('toCurrency', function (value) {
if (typeof value !== "number") {
return value;
}
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});
return formatter.format(value);
});
그러면 이렇게 필터를 사용할 수 있다.
<td class="text-right">
{{ invoice.fees | toCurrency }}
</td>
필터 구현을 돕기 위해 다음과 같은 관련 답변을 사용했다.
업데이트: @Jess에서 제공하는 필터와 함께 솔루션을 사용하는 것이 좋다.
나는 그것을 위한 방법을 쓰고, 그리고 가격을 포맷해야 하는 곳에 당신은 단지 템플릿에 메소드를 넣고 값을 낮추면 된다.
methods: {
formatPrice(value) {
let val = (value/1).toFixed(2).replace('.', ',')
return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".")
}
}
그런 다음 템플릿으로 다음을 수행하십시오.
<template>
<div>
<div class="panel-group"v-for="item in list">
<div class="col-md-8">
<small>
Total: <b>{{ formatPrice(item.total) }}</b>
</small>
</div>
</div>
</div>
</template>
BTW - 나는 교체와 정규 표현에 그다지 신경을 쓰지 않았다.그것은 개선될 수 있다.enter code here
Vue.filter('tableCurrency', num => {
if (!num) {
return '0.00';
}
const number = (num / 1).toFixed(2).replace(',', '.');
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
});
vuejs 2를 사용하면 다른 좋은 점도 있는 vue2 필터를 사용할 수 있다.
npm install vue2-filters
import Vue from 'vue'
import Vue2Filters from 'vue2-filters'
Vue.use(Vue2Filters)
그런 다음 이렇게 사용하십시오.
{{ amount | currency }} // 12345 => $12,345.00
참조: https://www.npmjs.com/package/vue2-filters
당신은 당신 자신의 코드를 쓰는 통화의 포맷을 할 수 있지만 그것은 단지 현재 해결책일 뿐이다 - 당신의 앱이 성장할 때 당신은 다른 통화를 필요로 할 수 있다.
이에 대한 또 다른 문제가 있다.
- EN-us의 경우 - 돌라 부호는 항상 통화 전 - $2.00,
- 선택된 PL의 경우, 당신은 2,00 zww와 같은 금액 뒤에 서명을 한다.
나는 도서관 vue-i18n(http://kazupon.github.io/vue-i18n/))과 같은 국제화를 위해 복잡한 솔루션을 사용하는 것이 최선의 선택이라고 생각한다.
나는 이 플러그 인을 사용하며 그런 걱정은 하지 않아도 된다.설명서를 참조하십시오. 정말 간단하다.
http://kazupon.github.io/vue-i18n/guide/number.html
따라서 다음을 사용하십시오.
<div id="app">
<p>{{ $n(100, 'currency') }}</p>
</div>
그리고 EN-us를 $100.00으로 설정:
<div id="app">
<p>$100.00</p>
</div>
또는 PL을 100,00 zw로 설정:
<div id="app">
<p>100,00 zł</p>
</div>
이 플러그인은 번역과 날짜 포맷과 같은 다른 기능도 제공한다.
@RoyJ의 코멘트에는 훌륭한 제안이 있다.템플릿에는 기본적으로 지역화된 문자열을 사용할 수 있으며,
<small>
Total: <b>{{ item.total.toLocaleString() }}</b>
</small>
일부 구형 브라우저에서는 지원되지 않지만, IE 11 이상을 대상으로 한다면 괜찮을 겁니다.
나는 @Jess에서 제안한 사용자 정의 필터 솔루션을 사용했지만 내 프로젝트에서는 TypeScript와 함께 Vue를 사용하고 있다.TypeScript와 클래스 장식가들의 모습은 다음과 같다.
import Component from 'vue-class-component';
import { Filter } from 'vue-class-decorator';
@Component
export default class Home extends Vue {
@Filter('toCurrency')
private toCurrency(value: number): string {
if (isNaN(value)) {
return '';
}
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 0
});
return formatter.format(value);
}
}
이 예에서 필터는 구성 요소 내부에서만 사용할 수 있다.나는 아직 그것을 글로벌 필터로 구현하려고 노력하지 않았다.
이 예제를 사용할 수 있다.
formatPrice(value) {
return value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
},
수용된 답변의 정확성에 문제가 있다.
이 테스트의 원형(값, 소수점) 함수 간단한 toFixed 예제와는 달리.
이것은 toFixed 대 둥근 방법의 시험이다.
http://www.jacklmoore.com/notes/rounding-in-javascript/
Number.prototype.format = function(n) {
return this.toFixed(Math.max(0, ~~n));
};
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
// can anyone tell me why these are equivalent for 50.005, and 1050.005 through 8150.005 (increments of 50)
var round_to = 2;
var maxInt = 1500000;
var equalRound = '<h1>BEGIN HERE</h1><div class="matches">';
var increment = 50;
var round_from = 0.005;
var expected = 0.01;
var lastWasMatch = true;
for( var n = 0; n < maxInt; n=n+increment){
var data = {};
var numberCheck = parseFloat(n + round_from);
data.original = numberCheck * 1;
data.expected = Number(n + expected) * 1;
data.formatIt = Number(numberCheck).format(round_to) * 1;
data.roundIt = round(numberCheck, round_to).toFixed(round_to) * 1;
data.numberIt = Number(numberCheck).toFixed(round_to) * 1;
//console.log(data);
if( data.roundIt !== data.formatIt || data.formatIt !== data.numberIt ||
data.roundIt !== data.numberIt || data.roundIt != data.expected
){
if(lastWasMatch){
equalRound = equalRound + '</div><div class="errors"> <hr/> Did Not Round UP <hr/>' ;
document.write(' <h3>EXAMPLE: Did Not Round UP: ' + numberCheck + '</h3><br /><hr/> ');
document.write('expected: '+data.expected + ' :: ' + (typeof data.expected) + '<br />');
document.write('format: '+data.formatIt + ' :: ' + (typeof data.formatIt) + '<br />');
document.write('round : '+data.roundIt + ' :: ' + (typeof data.roundIt) + '<br />');
document.write('number: '+data.numberIt + ' :: ' + (typeof data.numberIt) + '<br />');
lastWasMatch=false;
}
equalRound = equalRound + ', ' + numberCheck;
} else {
if(!lastWasMatch){
equalRound = equalRound + '</div><div class="matches"> <hr/> All Rounded UP! <hr/>' ;
} {
lastWasMatch=true;
}
equalRound = equalRound + ', ' + numberCheck;
}
}
document.write('equalRound: '+equalRound + '</div><br />');
혼합 예시
export default {
methods: {
roundFormat: function (value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals).toFixed(decimals);
},
currencyFormat: function (value, decimals, symbol='$') {
return symbol + this.roundFormat(value,2);
}
}
}
다음을 시도해 보십시오.
methods: {
formatPrice(value) {
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'PHP',
minimumFractionDigits: 2
});
return formatter.format(value);
},
}
그럼 그냥 이렇게 불러도 돼.
{{ formatPrice(item.total) }}
numeral.js는 숫자를 포맷하고 조작하기 위한 자바스크립트 라이브러리다.
화폐를 그렇게 쉽게 포맷할 수 있다.
예를 들어,
// price = 1200
{numeral(price).format(`$0,0.00`)}
// result $1,200.00
여기 문서가 있다.http://numeraljs.com/
참조URL: https://stackoverflow.com/questions/43208012/how-do-i-format-currencies-in-a-vue-component
'IT이야기' 카테고리의 다른 글
Python에서 __future_는 무엇에 사용되며 언제 어떻게/사용할 것인지, 그리고 어떻게 작동하는지. (0) | 2022.03.18 |
---|---|
Pytorch의 요약 (0) | 2022.03.18 |
UnicodeEncodeError: 'ascII' 코덱이 위치 20에서 문자 u'\xa0'을 인코딩할 수 없음: 서수가 범위(128)에 없음 (0) | 2022.03.18 |
rxjs 시간 초과 - 첫 번째 값 (0) | 2022.03.18 |
TouchableOpacity에 대한 "상승" 또는 Shadow 효과 생성:네이티브 리액션 (0) | 2022.03.18 |