GO·NOTE

一份 Go 开发工程师的学习笔记

0%

float64相加减

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

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

func main() {
x := 2.1
y := 0.8
fmt.Println(x+y)
fmt.Println(float64Add(x,y))
}

func float64Add(x float64, y float64, more ...float64) float64 {
floatX := new(big.Float).SetFloat64(x)
floatY := new(big.Float).SetFloat64(y)
result := new(big.Float).Add(floatX, floatY)
if len(more) > 0 {
for _, m := range more {
floatM := new(big.Float).SetFloat64(m)
result = new(big.Float).Add(result, floatM)
}
}
f, _ := strconv.ParseFloat(result.String(), 64) // 忽略 error
return f
}