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.
7 // decimal to binary floating point conversion.
9 // 1) Store input in multiprecision decimal.
10 // 2) Multiply/divide decimal by powers of two until in range [0.5, 1)
11 // 3) Multiply by 2^precision and round to get mantissa.
16 var optimize
= true // can change for testing
18 func equalIgnoreCase(s1
, s2
string) bool {
19 if len(s1
) != len(s2
) {
22 for i
:= 0; i
< len(s1
); i
++ {
24 if 'A' <= c1
&& c1
<= 'Z' {
28 if 'A' <= c2
&& c2
<= 'Z' {
38 func special(s
string) (f
float64, ok
bool) {
46 if equalIgnoreCase(s
, "+inf") ||
equalIgnoreCase(s
, "+infinity") {
47 return math
.Inf(1), true
50 if equalIgnoreCase(s
, "-inf") ||
equalIgnoreCase(s
, "-infinity") {
51 return math
.Inf(-1), true
54 if equalIgnoreCase(s
, "nan") {
55 return math
.NaN(), true
58 if equalIgnoreCase(s
, "inf") ||
equalIgnoreCase(s
, "infinity") {
59 return math
.Inf(1), true
65 func (b
*decimal
) set(s
string) (ok
bool) {
85 for ; i
< len(s
); i
++ {
95 case '0' <= s
[i
] && s
[i
] <= '9':
97 if s
[i
] == '0' && b
.nd
== 0 { // ignore leading zeros
104 } else if s
[i
] != '0' {
118 // optional exponent moves decimal point.
119 // if we read a very large, very long number,
120 // just be sure to move the decimal point by
121 // a lot (say, 100000). it doesn't matter if it's
122 // not the exact number.
123 if i
< len(s
) && (s
[i
] == 'e' || s
[i
] == 'E') {
131 } else if s
[i
] == '-' {
135 if i
>= len(s
) || s
[i
] < '0' || s
[i
] > '9' {
139 for ; i
< len(s
) && '0' <= s
[i
] && s
[i
] <= '9'; i
++ {
141 e
= e
*10 + int(s
[i
]) - '0'
155 // readFloat reads a decimal mantissa and exponent from a float
156 // string representation. It sets ok to false if the number could
157 // not fit return types or is invalid.
158 func readFloat(s
string) (mantissa
uint64, exp
int, neg
, trunc
, ok
bool) {
159 const uint64digits
= 19
180 for ; i
< len(s
); i
++ {
181 switch c
:= s
[i
]; true {
190 case '0' <= c
&& c
<= '9':
192 if c
== '0' && nd
== 0 { // ignore leading zeros
197 if ndMant
< uint64digits
{
199 mantissa
+= uint64(c
- '0')
201 } else if s
[i
] != '0' {
215 // optional exponent moves decimal point.
216 // if we read a very large, very long number,
217 // just be sure to move the decimal point by
218 // a lot (say, 100000). it doesn't matter if it's
219 // not the exact number.
220 if i
< len(s
) && (s
[i
] == 'e' || s
[i
] == 'E') {
228 } else if s
[i
] == '-' {
232 if i
>= len(s
) || s
[i
] < '0' || s
[i
] > '9' {
236 for ; i
< len(s
) && '0' <= s
[i
] && s
[i
] <= '9'; i
++ {
238 e
= e
*10 + int(s
[i
]) - '0'
256 // decimal power of ten to binary power of two.
257 var powtab
= []int{1, 3, 6, 9, 13, 16, 19, 23, 26}
259 func (d
*decimal
) floatBits(flt
*floatInfo
) (b
uint64, overflow
bool) {
263 // Zero is always a special case.
270 // Obvious overflow/underflow.
271 // These bounds are for 64-bit floats.
272 // Will have to change if we want to support 80-bit floats in the future.
283 // Scale by powers of two until in range [0.5, 1.0)
287 if d
.dp
>= len(powtab
) {
295 for d
.dp
< 0 || d
.dp
== 0 && d
.d
[0] < '5' {
297 if -d
.dp
>= len(powtab
) {
306 // Our range is [0.5,1) but floating point range is [1,2).
309 // Minimum representable exponent is flt.bias+1.
310 // If the exponent is smaller, move it up and
311 // adjust d accordingly.
312 if exp
< flt
.bias
+1 {
313 n
:= flt
.bias
+ 1 - exp
318 if exp
-flt
.bias
>= 1<<flt
.expbits
-1 {
322 // Extract 1+flt.mantbits bits.
323 d
.Shift(int(1 + flt
.mantbits
))
324 mant
= d
.RoundedInteger()
326 // Rounding might have added a bit; shift down.
327 if mant
== 2<<flt
.mantbits
{
330 if exp
-flt
.bias
>= 1<<flt
.expbits
-1 {
336 if mant
&(1<<flt
.mantbits
) == 0 {
344 exp
= 1<<flt
.expbits
- 1 + flt
.bias
349 bits
:= mant
& (uint64(1)<<flt
.mantbits
- 1)
350 bits |
= uint64((exp
-flt
.bias
)&(1<<flt
.expbits
-1)) << flt
.mantbits
352 bits |
= 1 << flt
.mantbits
<< flt
.expbits
354 return bits
, overflow
357 // Exact powers of 10.
358 var float64pow10
= []float64{
359 1e0
, 1e1
, 1e2
, 1e3
, 1e4
, 1e5
, 1e6
, 1e7
, 1e8
, 1e9
,
360 1e10
, 1e11
, 1e12
, 1e13
, 1e14
, 1e15
, 1e16
, 1e17
, 1e18
, 1e19
,
363 var float32pow10
= []float32{1e0
, 1e1
, 1e2
, 1e3
, 1e4
, 1e5
, 1e6
, 1e7
, 1e8
, 1e9
, 1e10
}
365 // If possible to convert decimal representation to 64-bit float f exactly,
366 // entirely in floating-point math, do so, avoiding the expense of decimalToFloatBits.
367 // Three common cases:
368 // value is exact integer
369 // value is exact integer * exact power of ten
370 // value is exact integer / exact power of ten
371 // These all produce potentially inexact but correctly rounded answers.
372 func atof64exact(mantissa
uint64, exp
int, neg
bool) (f
float64, ok
bool) {
373 if mantissa
>>float64info
.mantbits
!= 0 {
376 // gccgo gets this wrong on 32-bit i386 when not using -msse.
377 // See TestRoundTrip in atof_test.go for a test case.
378 if runtime
.GOARCH
== "386" {
381 f
= float64(mantissa
)
389 // Exact integers are <= 10^15.
390 // Exact powers of ten are <= 10^22.
391 case exp
> 0 && exp
<= 15+22: // int * 10^k
392 // If exponent is big but number of digits is not,
393 // can move a few zeros into the integer part.
395 f
*= float64pow10
[exp
-22]
398 if f
> 1e15 || f
< -1e15
{
399 // the exponent was really too large.
402 return f
* float64pow10
[exp
], true
403 case exp
< 0 && exp
>= -22: // int / 10^k
404 return f
/ float64pow10
[-exp
], true
409 // If possible to compute mantissa*10^exp to 32-bit float f exactly,
410 // entirely in floating-point math, do so, avoiding the machinery above.
411 func atof32exact(mantissa
uint64, exp
int, neg
bool) (f
float32, ok
bool) {
412 if mantissa
>>float32info
.mantbits
!= 0 {
415 f
= float32(mantissa
)
422 // Exact integers are <= 10^7.
423 // Exact powers of ten are <= 10^10.
424 case exp
> 0 && exp
<= 7+10: // int * 10^k
425 // If exponent is big but number of digits is not,
426 // can move a few zeros into the integer part.
428 f
*= float32pow10
[exp
-10]
431 if f
> 1e7 || f
< -1e7
{
432 // the exponent was really too large.
435 return f
* float32pow10
[exp
], true
436 case exp
< 0 && exp
>= -10: // int / 10^k
437 return f
/ float32pow10
[-exp
], true
442 const fnParseFloat
= "ParseFloat"
444 func atof32(s
string) (f
float32, err error
) {
445 if val
, ok
:= special(s
); ok
{
446 return float32(val
), nil
450 // Parse mantissa and exponent.
451 mantissa
, exp
, neg
, trunc
, ok
:= readFloat(s
)
453 // Try pure floating-point arithmetic conversion.
455 if f
, ok
:= atof32exact(mantissa
, exp
, neg
); ok
{
459 // Try another fast path.
461 if ok
:= ext
.AssignDecimal(mantissa
, exp
, neg
, trunc
, &float32info
); ok
{
462 b
, ovf
:= ext
.floatBits(&float32info
)
463 f
= math
.Float32frombits(uint32(b
))
465 err
= rangeError(fnParseFloat
, s
)
473 return 0, syntaxError(fnParseFloat
, s
)
475 b
, ovf
:= d
.floatBits(&float32info
)
476 f
= math
.Float32frombits(uint32(b
))
478 err
= rangeError(fnParseFloat
, s
)
483 func atof64(s
string) (f
float64, err error
) {
484 if val
, ok
:= special(s
); ok
{
489 // Parse mantissa and exponent.
490 mantissa
, exp
, neg
, trunc
, ok
:= readFloat(s
)
492 // Try pure floating-point arithmetic conversion.
494 if f
, ok
:= atof64exact(mantissa
, exp
, neg
); ok
{
498 // Try another fast path.
500 if ok
:= ext
.AssignDecimal(mantissa
, exp
, neg
, trunc
, &float64info
); ok
{
501 b
, ovf
:= ext
.floatBits(&float64info
)
502 f
= math
.Float64frombits(b
)
504 err
= rangeError(fnParseFloat
, s
)
512 return 0, syntaxError(fnParseFloat
, s
)
514 b
, ovf
:= d
.floatBits(&float64info
)
515 f
= math
.Float64frombits(b
)
517 err
= rangeError(fnParseFloat
, s
)
522 // ParseFloat converts the string s to a floating-point number
523 // with the precision specified by bitSize: 32 for float32, or 64 for float64.
524 // When bitSize=32, the result still has type float64, but it will be
525 // convertible to float32 without changing its value.
527 // If s is well-formed and near a valid floating point number,
528 // ParseFloat returns the nearest floating point number rounded
529 // using IEEE754 unbiased rounding.
531 // The errors that ParseFloat returns have concrete type *NumError
532 // and include err.Num = s.
534 // If s is not syntactically well-formed, ParseFloat returns err.Err = ErrSyntax.
536 // If s is syntactically well-formed but is more than 1/2 ULP
537 // away from the largest floating point number of the given size,
538 // ParseFloat returns f = ±Inf, err.Err = ErrRange.
539 func ParseFloat(s
string, bitSize
int) (float64, error
) {
542 return float64(f
), err