price.tsx 2.1 KB
Newer Older
宋宋 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
import React, { FunctionComponent } from 'react'
import './price.scss'
import bem from '@/utils/bem'

export interface PriceProps {
  price: number | string
  needSymbol: boolean
  symbol: string
  decimalDigits: number
  thousands: boolean
}
const defaultProps = {
  price: 0,
  needSymbol: true,
  symbol: '¥',
  decimalDigits: 2,
  thousands: false,
} as PriceProps
export const Price: FunctionComponent<Partial<PriceProps>> = (props) => {
  const { price, needSymbol, symbol, decimalDigits, thousands } = { ...defaultProps, ...props }
  const b = bem('price')
  const showSymbol = () => {
23
    return { __html: (needSymbol ? symbol : '') || '' }
宋宋 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37
  }
  const checkPoint = (price: string | number) => {
    return String(price).indexOf('.') > 0
  }
  const formatThousands = (num: any) => {
    if (Number(num) == 0) {
      num = 0
    }
    if (checkPoint(num)) {
      num = Number(num).toFixed(decimalDigits)
      num = typeof num.split('.') === 'string' ? num.split('.') : num.split('.')[0]
    } else {
      num = num.toString()
    }
38
    if (thousands) {
宋宋 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
      return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
    } else {
      return num
    }
  }
  const formatDecimal = (decimalNum: any) => {
    if (Number(decimalNum) == 0) {
      decimalNum = 0
    }
    if (checkPoint(decimalNum)) {
      decimalNum = Number(decimalNum).toFixed(decimalDigits)
      decimalNum = typeof decimalNum.split('.') === 'string' ? 0 : decimalNum.split('.')[1]
    } else {
      decimalNum = decimalNum.toString()
    }
    const result = '0.' + decimalNum
    const resultFixed = Number(result).toFixed(decimalDigits)
    return String(resultFixed).substring(2, resultFixed.length)
  }
  return (
    <div className="nut-price">
      {needSymbol ? (
        <div className={`${b('symbol')}`} dangerouslySetInnerHTML={showSymbol()}></div>
      ) : null}
      <div className={`${b('big')}`}>{formatThousands(price)}</div>
      <div className={`${b('point')}`}>.</div>
      <div className={`${b('small')}`}>{formatDecimal(price)}</div>
    </div>
  )
}

Price.defaultProps = defaultProps
Price.displayName = 'NutPrice'