float

package
v1.0.0-beta.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 12 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

float

Parsing and formatting of floating point numbers with locale-dependent separators (1.234,56, 1,234.56, 1'234.56, 1 234,56), rounding to decimal places, NaN/Inf checks, and a float type that decodes loose JSON. The money and strfmt packages parse numbers with this package.

import "github.com/domonda/go-types/float"

Generic helpers

All of them work on any type with the underlying type float32 or float64.

Function Description
RoundToDecimals[T](f T, decimals int) T Rounds half away from zero to decimals places, see Rounding. Negative decimals round to tens, hundreds, and so on: RoundToDecimals(1234.5, -2) is 1200.
DerefOr[T](ptr *T, defaultVal T) T *ptr, or defaultVal if ptr is nil.
Valid[T](f T) bool f is neither NaN nor ±Inf.
ValidAndHasSign[T](f T, sign int) bool Valid(f) and f has the sign of sign. sign == 0 matches any sign. Zero counts as positive: ValidAndHasSign(0, +1) is true, ValidAndHasSign(0, -1) is false, also for -0.
Rounding

RoundToDecimals and Format round half away from zero, and they round the shortest decimal representation of the float, which is the decimal literal that parses back to the same float, not its binary value:

Call Result math.Round/strconv on the binary value
RoundToDecimals(1.005, 2) 1.01 1 (binary 1.00499999999999989342)
RoundToDecimals(0.145, 2) 0.15 0.14
RoundToDecimals(2.5, 0) 3 3
Format(2.5, 0, '.', 0, false) "3" "2" (strconv rounds ties to even)
Format(0.125, 0, '.', 2, false) "0.13" "0.12"

float32 values round their shortest float32 decimal, so RoundToDecimals(float32(1.005), 2) is also 1.01. NaN, ±Inf, and values with no more decimal places than requested are returned unchanged. Only a rounded value beyond the range of T is ±Inf, like math.MaxFloat64 rounded to a multiple of 10^307. The money package rounds Amount and Rate the same way.

Parsing

Function Description
Parse(str string) (float64, error) ParseDetails without the details.
ParseDetails(str string) (f float64, thousandsSep, decimalSep rune, decimals int, err error) Parses str and returns the detected separators, 0 if not found, and the number of fractional digits before an exponent: "1.2e6" has 1 decimal. decimalSep is always 0, '.', or ','.

Rules of Parse and ParseDetails:

  • Leading and trailing whitespace is trimmed.
  • NaN, Inf, +Inf, and -Inf are the only non-finite inputs, matched exactly and case-sensitive. nan, Infinity, and -NaN are errors, and so is an out of range value like 1e999.
  • One sign, + or -, is allowed at the start or the end, also separated by a space: -12, - 12, 12-, and 12 - are all -12. A sign at both ends is an error, also if both agree: +12- and -12- are errors. A - right after the decimal separator means no cents and is no sign: 12,- and 12.- are 12.
  • Scientific notation with e or E and an optional exponent sign: 1.5e10, 2E-3. Separators in the exponent are errors.
  • . and , are decimal or thousands separators, ' and space are only thousands separators.
  • A single . or , is the decimal separator: "1,234" and "1.234" are 1.234, "1.000" is 1.
  • The same . or , repeated is the thousands separator: "1.234.567" is 1234567.
  • After a thousands separator, the other one of . and , is the decimal separator: "1.234,5" and "1,234.5" are 1234.5.
  • A single ' or space must be a thousands separator: "1'234" and "1 234" are 1234, "1'5" and "1 23" are errors.
  • Every thousands separator is followed by exactly 3 digits, and the group in front of the first one has 1 to 3 digits: "1234.567,89" and ".234,5" are errors.
  • A space can't follow another kind of thousands separator ("123,123 123"), and an apostrophe can't be the decimal separator ("1.234'5").
  • Hexadecimal numbers and _ digit separators are errors.
Input f thousandsSep decimalSep decimals
"1.234.567,89" 1234567.89 '.' ',' 2
"1,234.5" 1234.5 ',' '.' 1
"1'234.50" 1234.5 '\'' '.' 2
"1 234,56" 1234.56 ' ' ',' 2
"1,234" 1.234 0 ',' 3
"1'234" 1234 '\'' 0 0
"158,00 " 158 0 ',' 2
"1,234,567e3" 1234567e3 ',' 0 0

Formatting

func Format[T ~float32 | ~float64](
    f T,
    thousandsSep rune, // 0, ',', '.', '\'', or ' '
    decimalSep rune,   // '.' or ','
    precision int,     // -1 for the shortest exact form, otherwise fractional digits
    padPrecision bool, // pad the fraction with zeros to precision digits
) string
  • precision >= 0 rounds to that many fractional digits, see Rounding. precision == -1 writes the fewest digits that parse back to f exactly, and padPrecision has no effect.
  • padPrecision == true writes exactly precision fractional digits, false trims trailing zeros and a dangling decimal separator: Format(1.50, 0, '.', 2, false) is "1.5".
  • thousandsSep groups the integer part in groups of 3 digits. Grouping uses the rounded digits, so Format(999.995, ',', '.', 2, true) is "1,000.00".
  • The integer part is never written in exponent form: Format(1e21, ',', '.', -1, false) is "1,000,000,000,000,000,000,000".
  • NaN and ±Inf are returned as "NaN", "+Inf", and "-Inf" without grouping or padding.
  • float32 values are formatted with 32-bit precision: Format(float32(0.1), 0, '.', -1, false) is "0.1".
  • Format panics for an invalid thousandsSep or decimalSep, for thousandsSep == decimalSep, and for precision < -1.

FormatDef

type FormatDef struct {
    ThousandsSep rune `json:"thousandsSep,omitempty"`
    DecimalSep   rune `json:"decimalSep"`
    Precision    int  `json:"precision"`
    PadPrecision bool `json:"padPrecision"`
}

The arguments of Format as a struct, for storing a number format in a configuration. strfmt.FormatConfig uses it for floats.

Function / Method Description
NewFormatDef() *FormatDef &FormatDef{DecimalSep: '.', Precision: -1}: no grouping, dot decimal separator, shortest exact form.
(*FormatDef).Format(f float64) string Format(f, ThousandsSep, DecimalSep, Precision, PadPrecision) with '.' for a zero DecimalSep.
(*FormatDef).Parse(str string, langHints ...language.Code) (string, error) Parses str with Parse and returns it formatted with the definition: "1.234.567,89" becomes "1,234,567.89" for {',', '.', 2, true}. Ignores langHints.
FormatDef.MarshalJSON() ([]byte, error) See Serialization.
(*FormatDef).UnmarshalJSON(j []byte) error See Serialization.

Implements: json.Marshaler, json.Unmarshaler (pointer), strfmt.Parser (pointer). The zero FormatDef has DecimalSep 0, which Format and Parse write as '.', and Precision 0, which rounds to whole numbers: it formats 1234.5 as "1235". Start from NewFormatDef() for the shortest exact form.

Tolerant

type Tolerant float64

A float64 for JSON input that has numbers as strings, empty strings, or null.

Method Description
(*Tolerant).UnmarshalJSON(j) error See Serialization.
(*Tolerant).AsFloatPtr() *float64 The receiver as *float64, writes through it change the Tolerant.
Valid() bool Neither NaN nor ±Inf.
ValidAndGreaterZero() bool Valid and > 0.
ValidAndSmallerZero() bool Valid and < 0.
ValidAndHasSign(sign int) bool ValidAndHasSign(float64(f), sign).
IsNaN() bool, IsInf() bool NaN, or +Inf or -Inf.

Implements: json.Unmarshaler (pointer). There is no MarshalJSON.

Serialization

The package has no SQL support.

Type JSON written JSON accepted
FormatDef {"thousandsSep":",","decimalSep":".","precision":2,"padPrecision":true}. Separators are one-character strings, a zero ThousandsSep is omitted, a zero DecimalSep is "". One-character strings, "" for a zero separator, and the legacy code point strings like "44" for ',' that versions before the JSON methods wrote. Fields missing in the object keep their value. Strings of several characters, JSON numbers and separators that Format panics on, like "x" or the same rune for both, are errors, but a zero DecimalSep is accepted. It formats as '.', so it is an error with "." as thousandsSep. An error leaves the value unchanged.
Tolerant A JSON number via the float64 kind. NaN and ±Inf fail with json: unsupported value. Numbers, strings parsed with Parse after decoding JSON escapes ("1.234,56" is 1234.56), and null or "" as 0. "NaN", "Inf", "+Inf", "-Inf" as strings. An error leaves the value unchanged.

Gotchas

  • "1,234" is 1.234. A single . or , is always the decimal separator, so Format(1234, ',', '.', -1, false) writes "1,234", which Parse reads back as 1.234. This affects integers from 1000 to 999999 formatted with a thousands separator and without decimals. Write decimals to make the output unambiguous: Format(1234, ',', '.', 2, true) is "1,234.00", which parses back as 1234.
  • "1.000" is 1, not 1000. Parse German style integers with thousands separators only when they have at least two groups, or check the result against the expected magnitude.
  • A detected decimal separator can be 0. ParseDetails("1'234") returns decimalSep 0, which Format rejects with a panic. Pick a decimal separator that differs from thousandsSep before passing the detected separators back to Format.
  • Only FormatDef reads a zero decimal separator as '.'. The package function Format panics for it, and so does strfmt.Format for a float with a zero FormatConfig.Float.DecimalSep, because it passes the fields to Format.
  • Negative values that round to zero lose the sign. Format(-0.001, 0, '.', 2, true) is "0.00" and negative zero is "0", unlike strconv.FormatFloat, which writes "-0.00" and "-0". RoundToDecimals(-0.001, 2) still returns negative zero.
  • Tolerant can't tell missing from zero. JSON null, "", and 0 all decode to 0. Use a pointer field if the difference matters.
  • Unquoted NaN needs a direct call. Tolerant.UnmarshalJSON([]byte("NaN")) works, but json.Unmarshal rejects NaN as invalid JSON before calling it. Only the quoted "NaN" works through encoding/json.
  • Rounded floats are still binary floats. RoundToDecimals(0.145, 2) returns the float64 closest to 0.15. Use money.DecimalAmount or money.CentAmount for exact decimal arithmetic.

Examples

Parse numbers of unknown locale:

package main

import (
	"fmt"

	"github.com/domonda/go-types/float"
)

func main() {
	for _, s := range []string{"1.234.567,89", "1,234.5", "1'234", "1 234,56", "1,234", "12 -"} {
		f, thousandsSep, decimalSep, decimals, err := float.ParseDetails(s)
		fmt.Printf("%-14q %v %q %q %d %v\n", s, f, thousandsSep, decimalSep, decimals, err)
	}
	_, err := float.Parse("1'5")
	fmt.Println(err)

	// Output:
	// "1.234.567,89" 1.23456789e+06 '.' ',' 2 <nil>
	// "1,234.5"      1234.5 ',' '.' 1 <nil>
	// "1'234"        1234 '\'' '\x00' 0 <nil>
	// "1 234,56"     1234.56 ' ' ',' 2 <nil>
	// "1,234"        1.234 '\x00' ',' 3 <nil>
	// "12 -"         -12 '\x00' '\x00' 0 <nil>
	// thousands separators have to be 3 characters apart: "1'5"
}

Format and round:

package main

import (
	"fmt"

	"github.com/domonda/go-types/float"
)

func main() {
	fmt.Println(float.Format(1234567.891, '.', ',', 2, true))
	fmt.Println(float.Format(1234.5, ',', '.', 4, true))
	fmt.Println(float.Format(1234.5, '\'', '.', 2, false))
	fmt.Println(float.Format(0.125, 0, '.', 2, false))
	fmt.Println(float.Format(1234.0, ',', '.', -1, false)) // parses back as 1.234
	fmt.Println(float.RoundToDecimals(1.005, 2), float.RoundToDecimals(-2.5, 0))

	// Output:
	// 1.234.567,89
	// 1,234.5000
	// 1'234.5
	// 0.13
	// 1,234
	// 1.01 -3
}

Store a number format as JSON and decode loose JSON numbers:

package main

import (
	"encoding/json"
	"fmt"

	"github.com/domonda/go-types/float"
)

func main() {
	def := float.FormatDef{ThousandsSep: '.', DecimalSep: ',', Precision: 2, PadPrecision: true}
	j, err := json.Marshal(def)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(j))

	var legacy float.FormatDef
	err = json.Unmarshal([]byte(`{"thousandsSep":"44","decimalSep":"46","precision":-1}`), &legacy)
	fmt.Println(legacy.Format(1234567.5), err)

	var payment struct {
		Amounts []float.Tolerant `json:"amounts"`
	}
	err = json.Unmarshal([]byte(`{"amounts":[12.5,"1.234,56","",null,"NaN"]}`), &payment)
	fmt.Println(payment.Amounts, err)

	// Output:
	// {"thousandsSep":".","decimalSep":",","precision":2,"padPrecision":true}
	// 1,234,567.5 <nil>
	// [12.5 1234.56 0 0 NaN] <nil>
}
  • money: amount and rate parsing builds on ParseDetails, Amount and Rate rounding and formatting on RoundToDecimals and Format.
  • strfmt: scans floats with Parse and formats them with a FormatDef.
  • Lenient parsing: why a single separator is the decimal separator.
  • Money types and rounding: the shortest decimal rounding convention.
  • Scan and format table rows: FormatDef in strfmt.FormatConfig.

Documentation

Overview

Package float parses and formats floating point numbers with locale-dependent separators and rounds them to decimal places.

The package provides:

A single '.' or ',' is always the decimal separator, so "1,234" parses as 1.234 and not as 1234. The apostrophe and the space are only thousands separators, so "1'234" parses as 1234 and "1'5" is an error.

RoundToDecimals and Format round half away from zero, and they round the shortest decimal representation of a float instead of its binary value, so 1.005 rounds to 1.01 and 2.5 to 3.

See the README.md file of the package for the complete API reference, the JSON forms, and the known pitfalls.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DerefOr

func DerefOr[T ~float32 | ~float64](ptr *T, defaultVal T) T

DerefOr dereferences ptr or returns defaultVal if ptr is nil. Provides safe pointer dereferencing for float types.

func Format

func Format[T ~float32 | ~float64](f T, thousandsSep, decimalSep rune, precision int, padPrecision bool) string

Format a float similar to strconv.Format with the 'f' format option, but with decimalSep as decimal separator instead of a point and optional thousands grouping of the integer part. Valid values for decimalSep are '.' and ','. If thousandsSep is not zero, then the integer part of the number is grouped with thousandsSep between every group of 3 digits from right to left. Valid rune values for thousandsSep are 0, ',', '.', ' ', "'" and thousandsSep must be different from decimalSep. The precision argument is the number of fractional digits the value is rounded to half away from zero. Like RoundToDecimals it rounds the shortest decimal representation of f, which is the decimal literal that parses back to f, instead of its binary value, so 1.005 formats as "1.01" and 2.5 as "3" with precisions 2 and 0, where strconv.FormatFloat rounds the binary value 1.00499999999999989342 to "1.00" and the tie 2.5 to even. The special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Unlike by strconv.FormatFloat, negative zero and negative values that round to zero are formatted without a minus sign, like "0.00". If padPrecision is true, the fractional part is kept at exactly precision digits, padding the end with '0' characters when needed. If padPrecision is false, trailing fractional zeros are trimmed to return the shortest representation of the value rounded to precision. See: https://en.wikipedia.org/wiki/Decimal_separator

func Parse

func Parse(str string) (float64, error)

Parse a float string compatible with Format. It is ParseDetails without the detected separators and decimals, see ParseDetails for the separator rules. See: https://en.wikipedia.org/wiki/Decimal_separator

func ParseDetails

func ParseDetails(str string) (f float64, thousandsSep, decimalSep rune, decimals int, err error)

ParseDetails parses a float string compatible with Format and returns the detected integer thousands separator and decimal separator characters. If a separator was not detected, then zero will be returned for thousandsSep or decimalSep.

One sign, '+' or '-', may be the first or the last character, but not both, so "+1-" and "-1-" are errors. A '-' right after the decimal separator means no cents, so "12,-" and "12.-" are 12.

A single '.' or ',' is the decimal separator, so "1,234" parses as 1.234. The apostrophe and the space are only ever thousands separators, so "1'234" and "1 234" parse as 1234, and one that can't separate thousands, like in "1'5", is an error. Thousands separators have to be followed by exactly 3 digits and the group in front of the first one must have 1 to 3 digits. The returned decimalSep is always zero, '.' or ','. See: https://en.wikipedia.org/wiki/Decimal_separator

func RoundToDecimals

func RoundToDecimals[T ~float32 | ~float64](f T, decimals int) T

RoundToDecimals returns f rounded half away from zero to the passed number of decimal places. Negative decimals round to tens, hundreds, and so on.

It rounds the shortest decimal representation of f, which is the decimal literal that parses back to f, instead of its binary value, so RoundToDecimals(1.005, 2) is 1.01 and not the 1 of the binary value 1.00499999999999989342. Format rounds the same way.

NaN and ±Inf are returned unchanged, and so is a value that has no more decimal places than requested. Only a rounded value beyond the range of T, like math.MaxFloat64 rounded to a multiple of 10^307, is ±Inf.

func Valid

func Valid[T ~float32 | ~float64](f T) bool

Valid returns if the passed float is neither infinite nor NaN. Useful for validating float values before performing calculations.

func ValidAndHasSign

func ValidAndHasSign[T ~float32 | ~float64](f T, sign int) bool

ValidAndHasSign returns true if Valid(f) and if it has the same sign as the passed non-zero int argument. If 0 is passed as sign then the sign check always returns true.

Types

type FormatDef

type FormatDef struct {
	ThousandsSep rune `json:"thousandsSep,omitempty"`
	DecimalSep   rune `json:"decimalSep"`
	Precision    int  `json:"precision"`
	PadPrecision bool `json:"padPrecision"`
}

FormatDef holds the definition for a float format.

FormatDef implements encoding/json.Marshaler and encoding/json.Unmarshaler representing the separators as JSON strings of one character like "," or as empty string for a zero separator, see FormatDef.UnmarshalJSON. The json tags of the fields name the keys of that representation, but the separators are not written as numbers like their rune type.

func NewFormatDef

func NewFormatDef() *FormatDef

NewFormatDef returns a format definition with a dot as decimal separator and no precision limit.

func (*FormatDef) Format

func (ff *FormatDef) Format(f float64) string

Format formats the float64 value f using the thousands separator, decimal separator, precision, and padding settings defined in ff. A zero DecimalSep, like that of the zero FormatDef, formats a point, so FormatDef{Precision: -1} formats 1234.5 as "1234.5", where the package function Format panics for a zero decimalSep.

func (FormatDef) MarshalJSON

func (ff FormatDef) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler writing the separators as JSON strings of one character like "," or as empty string for a zero separator, where a zero ThousandsSep is omitted.

func (*FormatDef) Parse

func (ff *FormatDef) Parse(str string, langHints ...language.Code) (normalized string, err error)

Parse implements the strfmt.Parser interface. It parses str with the package function Parse and returns the value formatted with ff like FormatDef.Format, so a zero DecimalSep formats a point. The langHints are ignored.

func (*FormatDef) UnmarshalJSON

func (ff *FormatDef) UnmarshalJSON(j []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler reading the separators from JSON strings of one character like "," or from an empty string for a zero separator. Strings of decimal digits like "44" for ',' are read as the code point of the separator, which is how FormatDef was written before it implemented encoding/json.Marshaler. Fields missing in the JSON object keep their value. Separators and a precision that Format panics on are an error, like an invalid rune, the same rune for both separators, which a missing field that keeps its value can give, or a precision below -1, but a zero DecimalSep is accepted like for the zero FormatDef. It formats a point, so it is an error together with a point as ThousandsSep.

type Tolerant

type Tolerant float64

Tolerant is a float64 underneath that is tolerant in parsing non standard JSON

func (*Tolerant) AsFloatPtr

func (f *Tolerant) AsFloatPtr() *float64

AsFloatPtr returns f as *float64

func (Tolerant) IsInf

func (f Tolerant) IsInf() bool

IsInf returns if the float is positive or negative infinity

func (Tolerant) IsNaN

func (f Tolerant) IsNaN() bool

IsNaN returns if the float is not a number (NaN)

func (*Tolerant) UnmarshalJSON

func (f *Tolerant) UnmarshalJSON(j []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler and accepts numbers, strings, and null. JSON null and "" will set the amount to zero.

func (Tolerant) Valid

func (f Tolerant) Valid() bool

Valid returns if the float is neither infinite nor NaN

func (Tolerant) ValidAndGreaterZero

func (f Tolerant) ValidAndGreaterZero() bool

ValidAndGreaterZero returns if the float is neither infinite nor NaN and greater than zero.

func (Tolerant) ValidAndHasSign

func (f Tolerant) ValidAndHasSign(sign int) bool

ValidAndHasSign returns if a.Valid() and if it has the same sign than the passed int argument or any sign if 0 is passed.

func (Tolerant) ValidAndSmallerZero

func (f Tolerant) ValidAndSmallerZero() bool

ValidAndSmallerZero returns if the float is neither infinite nor NaN and smaller than zero.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL