FTOA is a specialized floating-point to string conversion library that implements JavaScript V8 engine's formatting behavior in Go. This library ensures consistent string representation of floating-point numbers between Go and JavaScript environments.
- 100% compatible with V8's JavaScript number formatting
- Handles all edge cases (NaN, Infinity, negative zero)
- Rounds .5 up in most cases
- Uses efficient Ryū algorithm for fast and accurate conversion
- Follows V8's scientific notation thresholds (≥1e21 or <1e-6)
go get github.com/nukilabs/ftoa
package main
import (
"fmt"
"github.com/nukilabs/ftoa"
)
func main() {
// Basic usage - equivalent to JavaScript's number.toString()
fmt.Println(ftoa.FormatFloat(123.456, 'g', -1, 64)) // "123.456"
// toFixed(2) equivalent
fmt.Println(ftoa.FormatFloat(123.456, 'f', 2, 64)) // "123.46"
// toExponential(2) equivalent
fmt.Println(ftoa.FormatFloat(123.456, 'e', 2, 64)) // "1.23e+2"
// Special values
fmt.Println(ftoa.FormatFloat(0.0/0.0, 'g', -1, 64)) // "NaN"
fmt.Println(ftoa.FormatFloat(1.0/0.0, 'g', -1, 64)) // "Infinity"
}number.toString()↔ftoa.FormatFloat(value, 'g', -1, 64)number.toFixed(n)↔ftoa.FormatFloat(value, 'f', n, 64)number.toExponential(n)↔ftoa.FormatFloat(value, 'e', n, 64)number.toPrecision(n)↔ftoa.FormatFloat(value, 'g', n, 64)
This library guarantees string representations identical to JavaScript's implicit string conversion (as if you were doing "" + number in JavaScript). Key differences from Go's standard library:
-
Scientific notation thresholds:
- V8: Scientific notation for values ≥1e21 or <1e-6
- Go: Different thresholds in standard library
-
Rounding behavior:
- V8: Rounds .5 up in most cases
- Go: Uses IEEE round-to-even by default
-
Formatting of special values:
- V8: "Infinity" and "NaN" (not "Inf" or "NaN")
- Go's standard formatting is different
When building systems that communicate between Go backends and JavaScript frontends, consistent string representation of numbers is critical for:
- JSON serialization
- API contracts
- Testing and validation
- Data interchange
FTOA ensures that floating-point numbers are formatted consistently across language boundaries.
This project is licensed under the MIT license that can be found in the LICENSE file.
- Based on Go's standard library decimal conversion algorithms
- Uses the Ryū algorithm for efficient binary-to-decimal conversion
- Carefully tuned to match V8's JavaScript number formatting
© 2025 nukilabs