# All files / utils formatStatValue.ts

20.69% Statements 6/29
0% Branches 0/18
0% Functions 0/2
25% Lines 6/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    601x
    1x
    1x

    1x

    1x

    1x

     import {isNumber} from './isNumber'
    import {isString} from './isString'
    import {preventNegativeZero} from './preventNegativeZero'

    import {DecimalPlaces} from '../types'

    export const MAX_DECIMAL_PLACES = 10

    interface FormatStatValueOptions {
      decimalPlaces?: DecimalPlaces
      prefix?: string
      suffix?: string
    }

    const getAutoDigits = (value: number | string): number => {
      const decimalIndex = value.toString().indexOf('.')

      return decimalIndex === -1 ? 0 : 2
    }

    export const formatStatValue = (
      value: number | string,
      {decimalPlaces, prefix, suffix}: FormatStatValueOptions = {}
    ): string => {
      let localeFormattedValue: undefined | string | number

      let digits: number

      if (decimalPlaces && decimalPlaces.isEnforced) {
        digits = decimalPlaces.digits
      } else {
        digits = getAutoDigits(value)
      }

      digits = Math.min(digits, MAX_DECIMAL_PLACES)

      if (isNumber(value)) {
        const [wholeNumber, fractionalNumber] = Number(value)
          .toFixed(digits)
          .split('.')

        localeFormattedValue = Number(wholeNumber).toLocaleString(undefined, {
          maximumFractionDigits: MAX_DECIMAL_PLACES,
        })

        if (fractionalNumber) {
          localeFormattedValue += `.${fractionalNumber}`
        }
      } else if (isString(value)) {
        localeFormattedValue = value
      } else {
        return 'Data cannot be displayed'
      }

      localeFormattedValue = preventNegativeZero(localeFormattedValue)
      const formattedValue = `${prefix || ''}${localeFormattedValue}${suffix || ''}`

      return formattedValue
    }