Golang cannot convert (variable of type decimal.Decimal) to float64

  1. Load the decimal package go get github.com/shopspring/decimal
  2. Structure Definition

Note: It is recommended to use json.Unmarshal(xx, &buyGoods{}) when the front-end parameter is converted into a structure containing decimal

import (
     "github.com/shopspring/decimal"
)
// buy item
type buyGoods struct {
     Num int `json:"num"` // number',
     Price decimal.Decimal `json:"price"` // unit price'
}

3.// First convert int to string and then convert to decimal type for operation
sellNum, _ := decimal.NewFromString(strconv.Itoa(e.Num))
totalMoney := MulDecimal(e.Price, sellNum)

4. the operation method corresponding to decimal

import "github.com/shopspring/decimal"
// Mainly used to handle floating point data precision
// addition
func AddDecimal(d1 decimal.Decimal, d2 decimal.Decimal) decimal.Decimal {
     return d1.Add(d2)
}
// subtract
func SubDecimal(d1 decimal.Decimal, d2 decimal.Decimal) decimal.Decimal {
     return d1.Sub(d2)
}
// multiply
func MulDecimal(d1 decimal.Decimal, d2 decimal.Decimal) decimal.Decimal {
     return d1.Mul(d2)
}
// division
func DivDecimal(d1 decimal.Decimal, d2 decimal.Decimal) decimal.Decimal {
     return d1.Div(d2)
}
// int
func IntDecimal(d decimal.Decimal) int64 {
     return d.IntPart()
}
// float
func FloatDecimal(d decimal.Decimal) float64 {
     f, exact := d.Float64()
     if !exact {
         return f
     }
     return 0
}

Leave a Reply

Your email address will not be published.

en_USEnglish