Go's strconv.FormatFloat in TypeScript

✓ Verified: Go 1.23
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { FormatFloat } from 'locutus/golang/strconv/FormatFloat'.

Or with CommonJS: const { FormatFloat } = require('locutus/golang/strconv/FormatFloat')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1FormatFloat(3.1415926, 'f', 2, 64)'3.14'
2FormatFloat(1200, 'e', 2, 64)'1.20e+03'
3FormatFloat(1200, 'E', 2, 64)'1.20E+03'
4FormatFloat(0.05, 'f', 0, 64)'0'

Notes

  • Supports common Go format verbs f/e/E/g/G.

  • For unsupported verbs this implementation throws.

  • Includes edge cases adapted from Go’s src/strconv/ftoa_test.go.

Here's what our current TypeScript equivalent to Go's strconv.FormatFloat looks like.

const padExponent = (value: string, upper = false): string => {
const replaced = value.replace(/e([+-]?)(\d+)$/i, (_m, signRaw: string, expDigits: string) => {
const sign = signRaw === '-' ? '-' : '+'
return `e${sign}${expDigits.padStart(2, '0')}`
})
return upper ? replaced.replace('e', 'E') : replaced
}

const trimTrailingZeroFraction = (value: string): string =>
value.replace(/(\.\d*?[1-9])0+$/u, '$1').replace(/\.0+$/u, '')

export function FormatFloat(f: number, fmt: string, prec: number, _bitSize: number): string {
// discuss at: https://locutus.io/golang/strconv/FormatFloat
// parity verified: Go 1.23
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Supports common Go format verbs f/e/E/g/G.
// note 2: For unsupported verbs this implementation throws.
// note 3: Includes edge cases adapted from Go's src/strconv/ftoa_test.go.
// example 1: FormatFloat(3.1415926, 'f', 2, 64)
// returns 1: '3.14'
// example 2: FormatFloat(1200, 'e', 2, 64)
// returns 2: '1.20e+03'
// example 3: FormatFloat(1200, 'E', 2, 64)
// returns 3: '1.20E+03'
// example 4: FormatFloat(0.05, 'f', 0, 64)
// returns 4: '0'

const value = Number(f)
const format = String(fmt)
const precision = Math.trunc(Number(prec))

if (!Number.isFinite(value)) {
return String(value)
}

switch (format) {
case 'f': {
if (precision < 0) {
return trimTrailingZeroFraction(value.toString())
}
return value.toFixed(precision)
}
case 'e': {
const rendered = precision < 0 ? value.toExponential() : value.toExponential(precision)
return padExponent(rendered, false)
}
case 'E': {
const rendered = precision < 0 ? value.toExponential() : value.toExponential(precision)
return padExponent(rendered, true)
}
case 'g':
case 'G': {
const rendered = precision < 0 ? value.toString() : value.toPrecision(Math.max(1, precision))
const normalized =
rendered.includes('e') || rendered.includes('E')
? padExponent(rendered, format === 'G')
: trimTrailingZeroFraction(rendered)
return format === 'G' ? normalized.replace('e', 'E') : normalized.replace('E', 'e')
}
default:
throw new Error(`strconv.FormatFloat: unsupported format ${format}`)
}
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


Help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More Go strconv functions


Star