1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Binary to decimal floating point conversion.
7 // 1) store mantissa in multiprecision decimal
8 // 2) shift decimal by exponent
9 // 3) read digits out & format
15 // TODO: move elsewhere?
16 type floatInfo
struct {
22 var float32info
= floatInfo
{23, 8, -127}
23 var float64info
= floatInfo
{52, 11, -1023}
25 // FormatFloat converts the floating-point number f to a string,
26 // according to the format fmt and precision prec. It rounds the
27 // result assuming that the original was obtained from a floating-point
28 // value of bitSize bits (32 for float32, 64 for float64).
30 // The format fmt is one of
31 // 'b' (-ddddp±ddd, a binary exponent),
32 // 'e' (-d.dddde±dd, a decimal exponent),
33 // 'E' (-d.ddddE±dd, a decimal exponent),
34 // 'f' (-ddd.dddd, no exponent),
35 // 'g' ('e' for large exponents, 'f' otherwise), or
36 // 'G' ('E' for large exponents, 'f' otherwise).
38 // The precision prec controls the number of digits (excluding the exponent)
39 // printed by the 'e', 'E', 'f', 'g', and 'G' formats.
40 // For 'e', 'E', and 'f' it is the number of digits after the decimal point.
41 // For 'g' and 'G' it is the maximum number of significant digits (trailing
42 // zeros are removed).
43 // The special precision -1 uses the smallest number of digits
44 // necessary such that ParseFloat will return f exactly.
45 func FormatFloat(f
float64, fmt
byte, prec
, bitSize
int) string {
46 return string(genericFtoa(make([]byte, 0, max(prec
+4, 24)), f
, fmt
, prec
, bitSize
))
49 // AppendFloat appends the string form of the floating-point number f,
50 // as generated by FormatFloat, to dst and returns the extended buffer.
51 func AppendFloat(dst
[]byte, f
float64, fmt
byte, prec
, bitSize
int) []byte {
52 return genericFtoa(dst
, f
, fmt
, prec
, bitSize
)
55 func genericFtoa(dst
[]byte, val
float64, fmt
byte, prec
, bitSize
int) []byte {
60 bits
= uint64(math
.Float32bits(float32(val
)))
63 bits
= math
.Float64bits(val
)
66 panic("strconv: illegal AppendFloat/FormatFloat bitSize")
69 neg
:= bits
>>(flt
.expbits
+flt
.mantbits
) != 0
70 exp
:= int(bits
>>flt
.mantbits
) & (1<<flt
.expbits
- 1)
71 mant
:= bits
& (uint64(1)<<flt
.mantbits
- 1)
74 case 1<<flt
.expbits
- 1:
85 return append(dst
, s
...)
92 // add implicit top bit
93 mant |
= uint64(1) << flt
.mantbits
97 // Pick off easy binary format.
99 return fmtB(dst
, neg
, mant
, exp
, flt
)
103 return bigFtoa(dst
, prec
, fmt
, neg
, mant
, exp
, flt
)
106 var digs decimalSlice
108 // Negative precision means "only as much as needed to be exact."
111 // Try Grisu3 algorithm.
113 lower
, upper
:= f
.AssignComputeBounds(mant
, exp
, neg
, flt
)
116 ok
= f
.ShortestDecimal(&digs
, &lower
, &upper
)
118 return bigFtoa(dst
, prec
, fmt
, neg
, mant
, exp
, flt
)
120 // Precision for shortest representation mode.
123 prec
= max(digs
.nd
-1, 0)
125 prec
= max(digs
.nd
-digs
.dp
, 0)
129 } else if fmt
!= 'f' {
130 // Fixed number of digits.
142 // try fast algorithm when the number of digits is reasonable.
145 f
:= extFloat
{mant
, exp
- int(flt
.mantbits
), neg
}
146 ok
= f
.FixedDecimal(&digs
, digits
)
150 return bigFtoa(dst
, prec
, fmt
, neg
, mant
, exp
, flt
)
152 return formatDigits(dst
, shortest
, neg
, digs
, prec
, fmt
)
155 // bigFtoa uses multiprecision computations to format a float.
156 func bigFtoa(dst
[]byte, prec
int, fmt
byte, neg
bool, mant
uint64, exp
int, flt
*floatInfo
) []byte {
159 d
.Shift(exp
- int(flt
.mantbits
))
160 var digs decimalSlice
163 roundShortest(d
, mant
, exp
, flt
)
164 digs
= decimalSlice
{d
: d
.d
[:], nd
: d
.nd
, dp
: d
.dp
}
165 // Precision for shortest representation mode.
170 prec
= max(digs
.nd
-digs
.dp
, 0)
175 // Round appropriately.
187 digs
= decimalSlice
{d
: d
.d
[:], nd
: d
.nd
, dp
: d
.dp
}
189 return formatDigits(dst
, shortest
, neg
, digs
, prec
, fmt
)
192 func formatDigits(dst
[]byte, shortest
bool, neg
bool, digs decimalSlice
, prec
int, fmt
byte) []byte {
195 return fmtE(dst
, neg
, digs
, prec
, fmt
)
197 return fmtF(dst
, neg
, digs
, prec
)
199 // trailing fractional zeros in 'e' form will be trimmed.
201 if eprec
> digs
.nd
&& digs
.nd
>= digs
.dp
{
204 // %e is used if the exponent from the conversion
205 // is less than -4 or greater than or equal to the precision.
206 // if precision was the shortest possible, use precision 6 for this decision.
211 if exp
< -4 || exp
>= eprec
{
215 return fmtE(dst
, neg
, digs
, prec
-1, fmt
+'e'-'g')
220 return fmtF(dst
, neg
, digs
, max(prec
-digs
.dp
, 0))
224 return append(dst
, '%', fmt
)
227 // roundShortest rounds d (= mant * 2^exp) to the shortest number of digits
228 // that will let the original floating point value be precisely reconstructed.
229 func roundShortest(d
*decimal
, mant
uint64, exp
int, flt
*floatInfo
) {
230 // If mantissa is zero, the number is zero; stop now.
236 // Compute upper and lower such that any decimal number
237 // between upper and lower (possibly inclusive)
238 // will round to the original floating point number.
240 // We may see at once that the number is already shortest.
242 // Suppose d is not denormal, so that 2^exp <= d < 10^dp.
243 // The closest shorter number is at least 10^(dp-nd) away.
244 // The lower/upper bounds computed below are at distance
245 // at most 2^(exp-mantbits).
247 // So the number is already shortest if 10^(dp-nd) > 2^(exp-mantbits),
248 // or equivalently log2(10)*(dp-nd) > exp-mantbits.
249 // It is true if 332/100*(dp-nd) >= exp-mantbits (log2(10) > 3.32).
250 minexp
:= flt
.bias
+ 1 // minimum possible exponent
251 if exp
> minexp
&& 332*(d
.dp
-d
.nd
) >= 100*(exp
-int(flt
.mantbits
)) {
252 // The number is already shortest.
256 // d = mant << (exp - mantbits)
257 // Next highest floating point number is mant+1 << exp-mantbits.
258 // Our upper bound is halfway between, mant*2+1 << exp-mantbits-1.
259 upper
:= new(decimal
)
260 upper
.Assign(mant
*2 + 1)
261 upper
.Shift(exp
- int(flt
.mantbits
) - 1)
263 // d = mant << (exp - mantbits)
264 // Next lowest floating point number is mant-1 << exp-mantbits,
265 // unless mant-1 drops the significant bit and exp is not the minimum exp,
266 // in which case the next lowest is mant*2-1 << exp-mantbits-1.
267 // Either way, call it mantlo << explo-mantbits.
268 // Our lower bound is halfway between, mantlo*2+1 << explo-mantbits-1.
271 if mant
> 1<<flt
.mantbits || exp
== minexp
{
278 lower
:= new(decimal
)
279 lower
.Assign(mantlo
*2 + 1)
280 lower
.Shift(explo
- int(flt
.mantbits
) - 1)
282 // The upper and lower bounds are possible outputs only if
283 // the original mantissa is even, so that IEEE round-to-even
284 // would round to the original mantissa and not the neighbors.
285 inclusive
:= mant%2
== 0
287 // Now we can figure out the minimum number of digits required.
288 // Walk along until d has distinguished itself from upper and lower.
289 for i
:= 0; i
< d
.nd
; i
++ {
290 l
:= byte('0') // lower digit
294 m
:= d
.d
[i
] // middle digit
295 u
:= byte('0') // upper digit
300 // Okay to round down (truncate) if lower has a different digit
301 // or if lower is inclusive and is exactly the result of rounding
302 // down (i.e., and we have reached the final digit of lower).
303 okdown
:= l
!= m || inclusive
&& i
+1 == lower
.nd
305 // Okay to round up if upper has a different digit and either upper
306 // is inclusive or upper is bigger than the result of rounding up.
307 okup
:= m
!= u
&& (inclusive || m
+1 < u || i
+1 < upper
.nd
)
309 // If it's okay to do either, then round to the nearest one.
310 // If it's okay to do only one, do it.
325 type decimalSlice
struct {
332 func fmtE(dst
[]byte, neg
bool, d decimalSlice
, prec
int, fmt
byte) []byte {
335 dst
= append(dst
, '-')
343 dst
= append(dst
, ch
)
347 dst
= append(dst
, '.')
349 m
:= min(d
.nd
, prec
+1)
351 dst
= append(dst
, d
.d
[i
:m
]...)
354 for ; i
<= prec
; i
++ {
355 dst
= append(dst
, '0')
360 dst
= append(dst
, fmt
)
362 if d
.nd
== 0 { // special case: 0 has exponent 0
371 dst
= append(dst
, ch
)
376 dst
= append(dst
, '0', byte(exp
)+'0')
378 dst
= append(dst
, byte(exp
/10)+'0', byte(exp%10
)+'0')
380 dst
= append(dst
, byte(exp
/100)+'0', byte(exp
/10)%10
+'0', byte(exp%10
)+'0')
386 // %f: -ddddddd.ddddd
387 func fmtF(dst
[]byte, neg
bool, d decimalSlice
, prec
int) []byte {
390 dst
= append(dst
, '-')
393 // integer, padded with zeros as needed.
396 dst
= append(dst
, d
.d
[:m
]...)
397 for ; m
< d
.dp
; m
++ {
398 dst
= append(dst
, '0')
401 dst
= append(dst
, '0')
406 dst
= append(dst
, '.')
407 for i
:= 0; i
< prec
; i
++ {
409 if j
:= d
.dp
+ i
; 0 <= j
&& j
< d
.nd
{
412 dst
= append(dst
, ch
)
419 // %b: -ddddddddp±ddd
420 func fmtB(dst
[]byte, neg
bool, mant
uint64, exp
int, flt
*floatInfo
) []byte {
423 dst
= append(dst
, '-')
427 dst
, _
= formatBits(dst
, mant
, 10, false, true)
430 dst
= append(dst
, 'p')
433 exp
-= int(flt
.mantbits
)
435 dst
= append(dst
, '+')
437 dst
, _
= formatBits(dst
, uint64(exp
), 10, exp
< 0, true)
442 func min(a
, b
int) int {
449 func max(a
, b
int) int {