function toFiniteNumber(value, fallback = 0) {
  if (typeof value === 'string') {
    const text = value.trim()
    const directValue = Number(text)
    if (Number.isFinite(directValue)) return directValue

    const match = text.match(/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/i)
    const textValue = match ? Number(match[0]) : NaN

    return Number.isFinite(textValue) ? textValue : fallback
  }

  const numberValue = Number(value)

  return Number.isFinite(numberValue) ? numberValue : fallback
}

function formatFixedValue(value, precision = 2) {
  const numberValue = toFiniteNumber(value, NaN)
  if (!Number.isFinite(numberValue)) return '--'

  const text = numberValue.toFixed(precision)
  return Number(text) === 0 ? (0).toFixed(precision) : text
}

module.exports = {
  formatFixedValue,
  toFiniteNumber
}
