# All files / utils formatStatValue.ts

100% Statements 25/25
93.75% Branches 15/16
100% Functions 2/2
100% Lines 22/22

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
    553x
    3x
    3x

    3x

    3x
    6x

    6x

    3x

    36x

    36x
    30x

    6x

    36x

    36x

    36x
    28x
    8x
    6x

    2x

    34x
    34x

    34x

     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)

      const formatter = Intl.NumberFormat(undefined, {
        minimumFractionDigits: digits,
        maximumFractionDigits: digits,
      })

      if (isNumber(value)) {
        localeFormattedValue = formatter.format(Number(value))
      } else if (isString(value)) {
        localeFormattedValue = value
      } else {
        return 'Data cannot be displayed'
      }

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

      return formattedValue
    }