jeol-t330a/succbone/succd/scientific.go

34 lines
540 B
Go

package main
import (
"fmt"
"strconv"
)
type ScientificNotationValue float64
func (s *ScientificNotationValue) UnmarshalText(text []byte) error {
f, err := strconv.ParseFloat(string(text), 64)
if err != nil {
return err
}
*s = ScientificNotationValue(f)
return nil
}
func (s *ScientificNotationValue) MarshalText() ([]byte, error) {
v := float64(*s)
exp := 0
for v < 1 {
v *= 10
exp -= 1
}
for v >= 10 {
v /= 10
exp += 1
}
res := fmt.Sprintf("%.3f", v)
res += fmt.Sprintf("e%d", exp)
return []byte(res), nil
}