(val float64, bits uint64, flt *floatInfo)
| 323 | } |
| 324 | |
| 325 | func newFromFloat(val float64, bits uint64, flt *floatInfo) Decimal { |
| 326 | if math.IsNaN(val) || math.IsInf(val, 0) { |
| 327 | panic(fmt.Sprintf("Cannot create a Decimal from %v", val)) |
| 328 | } |
| 329 | exp := int(bits>>flt.mantbits) & (1<<flt.expbits - 1) |
| 330 | mant := bits & (uint64(1)<<flt.mantbits - 1) |
| 331 | |
| 332 | switch exp { |
| 333 | case 0: |
| 334 | // denormalized |
| 335 | exp++ |
| 336 | |
| 337 | default: |
| 338 | // add implicit top bit |
| 339 | mant |= uint64(1) << flt.mantbits |
| 340 | } |
| 341 | exp += flt.bias |
| 342 | |
| 343 | var d decimal |
| 344 | d.Assign(mant) |
| 345 | d.Shift(exp - int(flt.mantbits)) |
| 346 | d.neg = bits>>(flt.expbits+flt.mantbits) != 0 |
| 347 | |
| 348 | roundShortest(&d, mant, exp, flt) |
| 349 | // If less than 19 digits, we can do calculation in an int64. |
| 350 | if d.nd < 19 { |
| 351 | tmp := int64(0) |
| 352 | m := int64(1) |
| 353 | for i := d.nd - 1; i >= 0; i-- { |
| 354 | tmp += m * int64(d.d[i]-'0') |
| 355 | m *= 10 |
| 356 | } |
| 357 | if d.neg { |
| 358 | tmp *= -1 |
| 359 | } |
| 360 | return Decimal{value: big.NewInt(tmp), exp: int32(d.dp) - int32(d.nd)} |
| 361 | } |
| 362 | dValue := new(big.Int) |
| 363 | dValue, ok := dValue.SetString(string(d.d[:d.nd]), 10) |
| 364 | if ok { |
| 365 | return Decimal{value: dValue, exp: int32(d.dp) - int32(d.nd)} |
| 366 | } |
| 367 | |
| 368 | return NewFromFloatWithExponent(val, int32(d.dp)-int32(d.nd)) |
| 369 | } |
| 370 | |
| 371 | // NewFromFloatWithExponent converts a float64 to Decimal, with an arbitrary |
| 372 | // number of fractional digits. |
no test coverage detected
searching dependent graphs…