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 // Package strconv implements conversions to and from string representations
6 // of basic data types.
9 // decimal to binary floating point conversion.
11 // 1) Store input in multiprecision decimal.
12 // 2) Multiply/divide decimal by powers of two until in range [0.5, 1)
13 // 3) Multiply by 2^precision and round to get mantissa.
18 var optimize
= true // can change for testing
20 func equalIgnoreCase(s1
, s2
string) bool {
21 if len(s1
) != len(s2
) {
24 for i
:= 0; i
< len(s1
); i
++ {
26 if 'A' <= c1
&& c1
<= 'Z' {
30 if 'A' <= c2
&& c2
<= 'Z' {
40 func special(s
string) (f
float64, ok
bool) {
48 if equalIgnoreCase(s
, "+inf") ||
equalIgnoreCase(s
, "+infinity") {
49 return math
.Inf(1), true
52 if equalIgnoreCase(s
, "-inf") ||
equalIgnoreCase(s
, "-infinity") {
53 return math
.Inf(-1), true
56 if equalIgnoreCase(s
, "nan") {
57 return math
.NaN(), true
60 if equalIgnoreCase(s
, "inf") ||
equalIgnoreCase(s
, "infinity") {
61 return math
.Inf(1), true
67 func (b
*decimal
) set(s
string) (ok
bool) {
87 for ; i
< len(s
); i
++ {
97 case '0' <= s
[i
] && s
[i
] <= '9':
99 if s
[i
] == '0' && b
.nd
== 0 { // ignore leading zeros
106 } else if s
[i
] != '0' {
120 // optional exponent moves decimal point.
121 // if we read a very large, very long number,
122 // just be sure to move the decimal point by
123 // a lot (say, 100000). it doesn't matter if it's
124 // not the exact number.
125 if i
< len(s
) && (s
[i
] == 'e' || s
[i
] == 'E') {
133 } else if s
[i
] == '-' {
137 if i
>= len(s
) || s
[i
] < '0' || s
[i
] > '9' {
141 for ; i
< len(s
) && '0' <= s
[i
] && s
[i
] <= '9'; i
++ {
143 e
= e
*10 + int(s
[i
]) - '0'
157 // readFloat reads a decimal mantissa and exponent from a float
158 // string representation. It sets ok to false if the number could
159 // not fit return types or is invalid.
160 func readFloat(s
string) (mantissa
uint64, exp
int, neg
, trunc
, ok
bool) {
161 const uint64digits
= 19
182 for ; i
< len(s
); i
++ {
183 switch c
:= s
[i
]; true {
192 case '0' <= c
&& c
<= '9':
194 if c
== '0' && nd
== 0 { // ignore leading zeros
199 if ndMant
< uint64digits
{
201 mantissa
+= uint64(c
- '0')
203 } else if s
[i
] != '0' {
217 // optional exponent moves decimal point.
218 // if we read a very large, very long number,
219 // just be sure to move the decimal point by
220 // a lot (say, 100000). it doesn't matter if it's
221 // not the exact number.
222 if i
< len(s
) && (s
[i
] == 'e' || s
[i
] == 'E') {
230 } else if s
[i
] == '-' {
234 if i
>= len(s
) || s
[i
] < '0' || s
[i
] > '9' {
238 for ; i
< len(s
) && '0' <= s
[i
] && s
[i
] <= '9'; i
++ {
240 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) (f
float64, err error
) {
541 f1
, err1
:= atof32(s
)
542 return float64(f1
), err1
544 f1
, err1
:= atof64(s
)