float_util.go 1019 Bytes
package webutility

import (
	"fmt"
	"math"
	"math/big"
)

func RoundFloat64(f float64, dec int) float64 {
	p := math.Pow(10, float64(dec))
	return math.Round(f*p) / p
}

func NewBF(f float64, prec uint) *big.Float {
	x := big.NewFloat(f)
	x.SetPrec(prec)
	return x
}

func AddBF(x, y *big.Float) *big.Float {
	z := big.NewFloat(0.0)
	z.SetPrec(x.Prec())
	z.Add(x, y)
	return z
}

func SubBF(x, y *big.Float) *big.Float {
	z := big.NewFloat(0.0)
	z.SetPrec(x.Prec())

	yneg := big.NewFloat(0.0)
	yneg.Neg(y)

	z.Add(x, yneg)
	return z
}

func MulBF(x, y *big.Float) *big.Float {
	z := big.NewFloat(0.0)
	z.SetPrec(x.Prec())
	z.Mul(x, y)
	return z
}

func DivBF(x, y *big.Float) *big.Float {
	z := big.NewFloat(0.0)
	z.SetPrec(x.Prec())
	z.Quo(x, y)
	return z
}

func BFtoFloat(f *big.Float) float64 {
	v, _ := f.Float64()
	return v
}

func Float64ToString(f float64) string {
	return fmt.Sprintf("%.2f", f)
}

func Float64PtrToString(f *float64) string {
	if f == nil {
		return ""
	}
	return fmt.Sprintf("%.2f", *f)
}