통화 포맷(필터)

7356 단어 filter필터

코드

//         (github: vuex --> demo --> shopping-cart -->currency.js)
const digitsRE = /(\d{3})(?=\d)/g
// value:     ; currency:     ; decimals    ;
export function currency (value, currency, decimals) {
     
  value = parseFloat(value)
  if (!isFinite(value) || (!value && value !== 0)) return ''
  currency = currency != null ? currency : '$'
  decimals = decimals != null ? decimals : 2
  var stringified = Math.abs(value).toFixed(decimals)
  var _int = decimals
    ? stringified.slice(0, -1 - decimals)
    : stringified
  var i = _int.length % 3
  var head = i > 0
    ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
    : ''
  var _float = decimals
    ? stringified.slice(-1 - decimals)
    : ''
  var sign = value < 0 ? '-' : ''
  return sign + currency + head +
    _int.slice(i).replace(digitsRE, '$1,') +
    _float
}


사용법


1, vue
//   (main.js)
import {
     currency} from './util/currency'
Vue.filter("currency",currency);

//   (   )
<div class="item-price">{
     {
     item.salePrice | currency('$')}}</div>

좋은 웹페이지 즐겨찾기