3

I'm looking for an algorithm that takes a 64-bit floating point number and outputs an exponent and coefficient so the input can be represented in the form float64 input = coefficient * 10 ^ exponent.

Supposedly this is 'not trivial', and many implementations of accurate decimal formats for Golang (which doesn't have a built-in decimal type) have some kind of hack for it like converting to a string and parsing that. While that solution does work in the packages I've seen, it just seems 'proper' to do it the mathematical/computer science-y way.

leylandski
  • 448
  • 1
  • 4
  • 15
  • Not really an answer, but if you're willing to try go1.5 you can look into [big.Float](https://github.com/golang/go/blob/master/src/math/big/float.go) – OneOfOne Aug 14 '15 at 14:12
  • 3
    I don't have time to format this into an answer (if you start walking through the code, you can see why), but converting a float64 to a string is basically the same operation, since the string representation is base 10. You can walk through the conversion starting at [strconv.AppendFloat](http://golang.org/src/strconv/ftoa.go), which has all the math. TLDR; using strconv isn't really that bad. – JimB Aug 14 '15 at 14:40
  • Oh, and if you want to see how the `fmt` package converts that to e+ notation, look for `fotmatFloat` in `fmt/format.go`. – JimB Aug 14 '15 at 14:45

1 Answers1

0

It may be not 100% precise, but you can use Log10:

package main

import (
  "fmt"
  "math"
)

func parts(v float64) (float64, int) {
  e := math.Floor(math.Log10(v))
  c := v / math.Pow(10, e)
  return c, int(e)
}

func main() {
  c, e := parts(1348.234e134)
  fmt.Printf("%v * 10^%v", c, e) // 1.3482339999999997 * 10^137
}
Alex Netkachov
  • 13,172
  • 6
  • 53
  • 85