golang 金额高精度计算

1,240 阅读1分钟
package main

import (
	"encoding/json"
	"fmt"
	amountdecimal "github.com/jishulangcom/go-amount-decimal"
	"math/big"
)

func main() {
	var f float64 = 0.5 // 【"float32", "float64"】
	var s string = "1"
	var i int = 2 // 【"int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64"】
	var j json.Number = json.Number("3")
	bi := new(big.Int).SetInt64(4) // *big.Int
	var decimal int = 5

	//---------------------【基本用法】-----------------------------------------------------------------------
	// 0.5+1 = (1.5)-2 = (-0.5)*3 = (-1.5)/4
	// Calculated in order from left to right
	amountB1, errB1 := amountdecimal.New(f).Add(s).Sub(i).Mul(j).Div(bi).ToString(decimal)
	fmt.Println("【基本用法】:", amountB1, errB1) // -0.37500 <nil>

	//---------------------【指定金额类型】-----------------------------------------------------------
	// 0.5 +1 +2 +3 +4 +5
	amountS1, errS1 := amountdecimal.NewFloat64(f).AddInt(i).ToString(decimal)
	fmt.Println("【指定金额类型】:", amountS1, errS1) // 2.50000 <nil>

	//---------------------【多个金额传参】-----------------------------------------------------------
	// 0.5 +1 +2 +3 +4 +5
	amountM1, errM1 := amountdecimal.New(f).Add(s, i, j, bi).ToString(decimal)
	fmt.Println("【多个金额传参】:", amountM1, errM1) // 10.50000 <nil>

	//---------------------【虚拟币精度计算】------------------------------------------------------------------------
	amount := 100
	fee := 0.001
	amountC1, errC1 := amountdecimal.New(amount).Mul(fee).ToString("BTC")
	fmt.Println("【虚拟币精度计算1】:", amountC1, errC1) // 0.10000000 <nil>

	amountC2, errC2 := amountdecimal.New(amount).Mul(fee).ToBigInt(amountdecimal.COIN_BTC)
	fmt.Println("【虚拟币精度计算2】:", amountC2, errC2) // 10000000 <nil>

	amountC3, errC3 := amountdecimal.BigIntActualAmount(amountC2, amountdecimal.COIN_BTC_DECIMAL)
	fmt.Println("【虚拟币精度计算3】:", amountC3, errC3) // 10000000 <nil>
}