go decimal 使用方法

本文介绍了如何在Go中导入和使用github.com/shopspring/decimal包进行高精度浮点数运算,包括结构定义、转换及加减乘除等操作,确保在前端传参和计算过程中避免精度损失。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、载入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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值