// Package floatfmt writes floats as JSON numbers, by their shortest decimal, as ECMA-262 formats numbers: the // format of encoding/json and of encoding/json/jsontext.
package floatfmt import ( ) // The floats are written by their shortest decimal, which is found as Raffaello Giulietti finds it in "The // Schubfach way to render doubles" (2020): of the decimals which round to the float, the one of the fewest // digits, and of those, the one closest to the float, or the one of an even last digit where two are as close. //go:generate go run ../cmd/float_table float_table.go // AppendFloat appends the finite float f, of the precision bits, 64 or 32, as ECMA-262, 10th edition, section // 7.1.12.1 formats a number, except that -0 is -0: as strconv.AppendFloat with the format 'f', or 'e' below 1e-6 // and from 1e21, whose exponent has no leading zero, writes it. func ( []byte, float64, int) []byte { if == 32 { = float64(float32()) } // an integer below 2⁵³, or 2²⁴ for 32 bits, is the only integer which rounds to its float: its digits are the // shortest. := int64(1) << 53 if == 32 { = 1 << 24 } if := int64(); float64() == && != 0 && - < && < { return strconv.AppendInt(, , 10) } return appendShortestFloat(, , ) } // The range of the exponents k of the powers of ten of floatPow10. const ( floatKMin = -324 floatKMax = 292 ) // floatFormat is the form of the floats of a size: the bits of the significand without its hidden bit, the // bits of the exponent, and the least exponent of the significand as an integer. type floatFormat struct { fracBits uint expMask uint64 qMin int } var ( float64Format = floatFormat{fracBits: 52, expMask: 0x7ff, qMin: -1074} float32Format = floatFormat{fracBits: 23, expMask: 0xff, qMin: -149} ) // shortestDecimal returns the shortest decimal d·10ᵉ of the finite float of the size fm, which is not zero, // whose sign and exponent and significand are given as the bits of IEEE 754. d may end with zeros. func shortestDecimal( uint64, *floatFormat) (uint64, int) { := & (1<<.fracBits - 1) := int(>>.fracBits) & int(.expMask) if == 0 { // a subnormal float return schubfach(.qMin, , ) } return schubfach(-1+.qMin, 1<<.fracBits|, ) } // schubfach returns the shortest decimal of c·2^q. Unlike the paper, which writes at least two digits, it looks // for a decimal of one digit less for any s of two digits or more, and scales no significand. func schubfach( int, uint64, *floatFormat) (uint64, int) { := & 1 // a significand which is even rounds its halfway points to itself: they are in its interval := << 2 := + 2 var uint64 var int if != 1<<.fracBits || == .qMin { = - 2 = floorLog10Pow2() } else { // the float below a power of two is nearer than the one above it = - 1 = floorLog10ThreeQuartersPow2() } := + floorLog2Pow10(-) + 2 := &floatPow10[-floatKMin] := roundOdd(, <<uint()) := roundOdd(, <<uint()) := roundOdd(, <<uint()) // The choices are made by arithmetic, not by branches, which the digits of the floats would mispredict. // Of s and s+1, one or both are in the interval: the decimal is s+1 where s is not, or where both are and // s+1 is closer to the float, or as close and even. := >> 2 := bit(+ <= <<2) := bit((+1)<<2+ <= ) := <<2 + 2 := + (1 - | &(bit( > )|bit( == )&)) if >= 10 { // a decimal of one digit less, which is the decimal if only one of its neighbors is in the interval: the // interval is narrower than ten of the last digit of s, and has one of them at most. It is returned // without its last digit, which is 0. := / 10 := bit(+ <= *10<<2) := bit((+1)*10<<2+ <= ) := -( ^ ) = &^ | (+)& += int( & 1) } return , } // bit is 1 for true and 0 for false. func bit( bool) uint64 { if { return 1 } return 0 } // roundOdd returns g·cp / 2¹²⁷, where g is the 126 bits of its high and low 63 bits, rounded to odd: its // lowest bit is set if it is not exact. func roundOdd( *[2]uint64, uint64) uint64 { , := bits.Mul64([1], ) , := bits.Mul64([0], ) := >>1 + := + >>63 return | (&(1<<63-1)+(1<<63-1))>>63 } // ⌊e·log₁₀2⌋, ⌊log₁₀(¾·2ᵉ)⌋ and ⌊e·log₂10⌋, exact for the exponents of floats. // They take 64 bits, which an int of 32 bits doesn't have. func floorLog10Pow2( int) int { return int(int64() * 661971961083 >> 41) } func floorLog10ThreeQuartersPow2( int) int { return int((int64()*661971961083 - 274743187321) >> 41) } func floorLog2Pow10( int) int { return int(int64() * 913124641741 >> 38) } // appendShortestFloat appends the finite float f of the size, 64 or 32, as ECMA-262, 10th edition, section // 7.1.12.1 formats a number, except that -0 is -0. func appendShortestFloat( []byte, float64, int) []byte { var uint64 := &float64Format if == 32 { , = uint64(math.Float32bits(float32())), &float32Format } else { = math.Float64bits() } if math.Signbit() { = append(, '-') } if == 0 { return append(, '0') } , := shortestDecimal(, ) for %10 == 0 { /= 10 ++ } // the digits, the lowest ones by blocks of eight, whose divisions don't wait for each other var [24]byte := len() for >= 1e8 { -= 8 put8Digits([:+8], uint32(%1e8)) /= 1e8 } for ; >= 100; /= 100 { -= 2 copy([:+2], twoDigits[%100*2:]) } if >= 10 { -= 2 copy([:+2], twoDigits[*2:]) } else { -- [] = byte('0' + ) } := [:] // the decimal is 0.digits·10ⁿ := + len() switch { case len() <= && <= 21: = append(, ...) for range - len() { = append(, '0') } case 0 < && <= 21: = append(, [:]...) = append(, '.') = append(, [:]...) case -6 < && <= 0: = append(, "0."...) for range - { = append(, '0') } = append(, ...) default: = append(, [0]) if len() > 1 { = append(, '.') = append(, [1:]...) } = append(, 'e') := - 1 if < 0 { = append(, '-') = - } else { = append(, '+') } if >= 100 { = append(, byte('0'+/100)) = append(, twoDigits[%100*2:%100*2+2]...) } else if >= 10 { = append(, twoDigits[*2:*2+2]...) } else { = append(, byte('0'+)) } } return } // put8Digits writes the eight digits of v, which is below 10⁸, to b, by dividing the parts of v in the lanes of // a word at once: its halves of four digits, then their halves of two digits, then their digits, the first one // in the lowest lane, which is the first byte that the word is stored as. func put8Digits( []byte, uint32) { := uint64(/1e4) | uint64(%1e4)<<32 // n/100 is n·10486 >> 20 for n below 10⁴, and n/10 is n·103 >> 10 for n below 100: the products don't // reach the bits of the lanes which are kept. := * 10486 >> 20 & 0x0000007f_0000007f = | (-*100)<<16 = * 103 >> 10 & 0x000f000f_000f000f = | (-*10)<<8 binary.LittleEndian.PutUint64(, |0x30303030_30303030) } // twoDigits are the numbers from 00 to 99. const twoDigits = "00010203040506070809101112131415161718192021222324252627282930313233343536373839" + "40414243444546474849505152535455565758596061626364656667686970717273747576777879" + "8081828384858687888990919293949596979899"