栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

go decimal 使用方法

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

go decimal 使用方法

一、载入decimal包

     go get  github.com/shopspring/decimal

二、结构定义

注意:前端传参转成包含decimal的结构时,建议使用 json.Unmarshal(xx, &buyGoods{})  

import (
    "github.com/shopspring/decimal"
)
// 购买商品
type buyGoods struct {
    Num          int             `json:"num"`          // 数量',
    Price        decimal.Decimal `json:"price"`        // 单价'
}

三、逻辑使用

// 先将int 转成string 再转成 decimal类型去运算
sellNum, _ := decimal.NewFromString(strconv.Itoa(e.Num)) 
totalMoney := MulDecimal(e.Price, sellNum)

四、对应decimal的运算方法

import "github.com/shopspring/decimal"

// 主要用于处理浮点数据精度

// 加法
func AddDecimal(d1 decimal.Decimal, d2 decimal.Decimal) decimal.Decimal {
    return d1.Add(d2)
}

// 减法
func SubDecimal(d1 decimal.Decimal, d2 decimal.Decimal) decimal.Decimal {
    return d1.Sub(d2)
}

// 乘法
func MulDecimal(d1 decimal.Decimal, d2 decimal.Decimal) decimal.Decimal {
    return d1.Mul(d2)
}

// 除法
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
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/908015.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号