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
39 // (excluding the exponent) 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 total number of digits.
42 // The special precision -1 uses the smallest number of digits
43 // necessary such that ParseFloat will return f exactly.
44 func FormatFloat(f
float64, fmt
byte, prec
, bitSize
int) string {
45 return string(genericFtoa(make([]byte, 0, max(prec
+4, 24)), f
, fmt
, prec
, bitSize
))
48 // AppendFloat appends the string form of the floating-point number f,
49 // as generated by FormatFloat, to dst and returns the extended buffer.
50 func AppendFloat(dst
[]byte, f
float64, fmt
byte, prec
int, bitSize
int) []byte {
51 return genericFtoa(dst
, f
, fmt
, prec
, bitSize
)
54 func genericFtoa(dst
[]byte, val
float64, fmt
byte, prec
, bitSize
int) []byte {
59 bits
= uint64(math
.Float32bits(float32(val
)))
62 bits
= math
.Float64bits(val
)
65 panic("strconv: illegal AppendFloat/FormatFloat bitSize")
68 neg
:= bits
>>(flt
.expbits
+flt
.mantbits
) != 0
69 exp
:= int(bits
>>flt
.mantbits
) & (1<<flt
.expbits
- 1)
70 mant
:= bits
& (uint64(1)<<flt
.mantbits
- 1)
73 case 1<<flt
.expbits
- 1:
84 return append(dst
, s
...)
91 // add implicit top bit
92 mant |
= uint64(1) << flt
.mantbits
96 // Pick off easy binary format.
98 return fmtB(dst
, neg
, mant
, exp
, flt
)
102 return bigFtoa(dst
, prec
, fmt
, neg
, mant
, exp
, flt
)
105 var digs decimalSlice
107 // Negative precision means "only as much as needed to be exact."
110 // Try Grisu3 algorithm.
112 lower
, upper
:= f
.AssignComputeBounds(mant
, exp
, neg
, flt
)
115 ok
= f
.ShortestDecimal(&digs
, &lower
, &upper
)
117 return bigFtoa(dst
, prec
, fmt
, neg
, mant
, exp
, flt
)
119 // Precision for shortest representation mode.
124 prec
= max(digs
.nd
-digs
.dp
, 0)
128 } else if fmt
!= 'f' {
129 // Fixed number of digits.
141 // try fast algorithm when the number of digits is reasonable.
144 f
:= extFloat
{mant
, exp
- int(flt
.mantbits
), neg
}
145 ok
= f
.FixedDecimal(&digs
, digits
)
149 return bigFtoa(dst
, prec
, fmt
, neg
, mant
, exp
, flt
)
151 return formatDigits(dst
, shortest
, neg
, digs
, prec
, fmt
)
154 // bigFtoa uses multiprecision computations to format a float.
155 func bigFtoa(dst
[]byte, prec
int, fmt
byte, neg
bool, mant
uint64, exp
int, flt
*floatInfo
) []byte {
158 d
.Shift(exp
- int(flt
.mantbits
))
159 var digs decimalSlice
162 roundShortest(d
, mant
, exp
, flt
)
163 digs
= decimalSlice
{d
: d
.d
[:], nd
: d
.nd
, dp
: d
.dp
}
164 // Precision for shortest representation mode.
169 prec
= max(digs
.nd
-digs
.dp
, 0)
174 // Round appropriately.
186 digs
= decimalSlice
{d
: d
.d
[:], nd
: d
.nd
, dp
: d
.dp
}
188 return formatDigits(dst
, shortest
, neg
, digs
, prec
, fmt
)
191 func formatDigits(dst
[]byte, shortest
bool, neg
bool, digs decimalSlice
, prec
int, fmt
byte) []byte {
194 return fmtE(dst
, neg
, digs
, prec
, fmt
)
196 return fmtF(dst
, neg
, digs
, prec
)
198 // trailing fractional zeros in 'e' form will be trimmed.
200 if eprec
> digs
.nd
&& digs
.nd
>= digs
.dp
{
203 // %e is used if the exponent from the conversion
204 // is less than -4 or greater than or equal to the precision.
205 // if precision was the shortest possible, use precision 6 for this decision.
210 if exp
< -4 || exp
>= eprec
{
214 return fmtE(dst
, neg
, digs
, prec
-1, fmt
+'e'-'g')
219 return fmtF(dst
, neg
, digs
, max(prec
-digs
.dp
, 0))
223 return append(dst
, '%', fmt
)
226 // Round d (= mant * 2^exp) to the shortest number of digits
227 // that will let the original floating point value be precisely
228 // reconstructed. Size is original floating point size (64 or 32).
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 var l
, m
, u
byte // lower, middle, upper digits
303 // Okay to round down (truncate) if lower has a different digit
304 // or if lower is inclusive and is exactly the result of rounding down.
305 okdown
:= l
!= m ||
(inclusive
&& l
== m
&& i
+1 == lower
.nd
)
307 // Okay to round up if upper has a different digit and
308 // either upper is inclusive or upper is bigger than the result of rounding up.
309 okup
:= m
!= u
&& (inclusive || m
+1 < u || i
+1 < upper
.nd
)
311 // If it's okay to do either, then round to the nearest one.
312 // If it's okay to do only one, do it.
327 type decimalSlice
struct {
334 func fmtE(dst
[]byte, neg
bool, d decimalSlice
, prec
int, fmt
byte) []byte {
337 dst
= append(dst
, '-')
345 dst
= append(dst
, ch
)
349 dst
= append(dst
, '.')
351 m
:= d
.nd
+ prec
+ 1 - max(d
.nd
, prec
+1)
353 dst
= append(dst
, d
.d
[i
])
357 dst
= append(dst
, '0')
363 dst
= append(dst
, fmt
)
365 if d
.nd
== 0 { // special case: 0 has exponent 0
374 dst
= append(dst
, ch
)
381 buf
[i
] = byte(exp%10
+ '0')
386 buf
[i
] = byte(exp
+ '0')
390 dst
= append(dst
, buf
[0], buf
[1], buf
[2])
392 dst
= append(dst
, buf
[1], buf
[2])
395 dst
= append(dst
, '0', buf
[2])
400 // %f: -ddddddd.ddddd
401 func fmtF(dst
[]byte, neg
bool, d decimalSlice
, prec
int) []byte {
404 dst
= append(dst
, '-')
407 // integer, padded with zeros as needed.
410 for i
= 0; i
< d
.dp
&& i
< d
.nd
; i
++ {
411 dst
= append(dst
, d
.d
[i
])
413 for ; i
< d
.dp
; i
++ {
414 dst
= append(dst
, '0')
417 dst
= append(dst
, '0')
422 dst
= append(dst
, '.')
423 for i
:= 0; i
< prec
; i
++ {
425 if j
:= d
.dp
+ i
; 0 <= j
&& j
< d
.nd
{
428 dst
= append(dst
, ch
)
435 // %b: -ddddddddp+ddd
436 func fmtB(dst
[]byte, neg
bool, mant
uint64, exp
int, flt
*floatInfo
) []byte {
439 exp
-= int(flt
.mantbits
)
446 for exp
> 0 || n
< 1 {
449 buf
[w
] = byte(exp%10
+ '0')
457 for mant
> 0 || n
< 1 {
460 buf
[w
] = byte(mant%10
+ '0')
467 return append(dst
, buf
[w
:]...)
470 func max(a
, b
int) int {