Thanks Robert,
It is great! a, _ := decimal.NewFromString("0.1") b, _ := decimal.NewFromString("0.2") c := a.Add(b) fmt.Println("decimal:", c) a = decimal.NewFromFloat(0.1) b = decimal.NewFromFloat(0.2) c = a.Add(b) fmt.Println("decimal:", c) a, _ = decimal.NewFromString("0.1") b, _ = decimal.NewFromString("0.35") c = a.Add(b) fmt.Println("decimal:", c) a = decimal.NewFromFloat(0.1) b = decimal.NewFromFloat(0.35) c = a.Add(b) fmt.Println("decimal:", c) /* $ go build && ./main decimal: 0.3 decimal: 0.3 decimal: 0.45 decimal: 0.45 $ */ ------------------ Original ------------------ From: "Robert Engels"<reng...@ix.netcom.com>; Date: 2022年4月9日(星期六) 晚上10:22 To: "Jack Li"<ljh_...@qq.com>; Cc: "golang-nuts"<golang-nuts@googlegroups.com>; Subject: Re: [go-nuts] float exactness There are several. See github.com/robaho/fixed As to why, read up on numerical analysis. It’s an interesting topic. On Apr 9, 2022, at 8:56 AM, 'Jack Li' via golang-nuts <golang-nuts@googlegroups.com> wrote: Hi group, 1. Is there a package can do exact float operations, like Decimal in Python? For example: x := 0.1; y := 0.2; z := x + y; z will be exact 0.3 2. Why literal operation is exact, variable is not? fmt.Println(0.1 + 0.2) // 0.3 exactly fmt.Println(x + y) // 0.30000000000000004 Thanks func main() { x := 0.1 y := 0.2 fmt.Println("x + y :", x + y) fmt.Println("literal:", 0.1 + 0.2) x = 0.1 y = 0.35 fmt.Println("x + y :", x + y) fmt.Println("literal:", 0.1 + 0.35) } /* $ go build && ./main x + y : 0.30000000000000004 literal: 0.3 x + y : 0.44999999999999996 literal: 0.45 $ */ // Python: // >>> 0.1 + 0.2 // 0.30000000000000004 // >>> float(Decimal('0.1') + Decimal('0.2')) // 0.3 // >>> // >>> 0.35 + 0.1 // 0.44999999999999996 // >>> float(Decimal('0.35') + Decimal('0.1')) // 0.45 // >>> -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/tencent_327903B1334351F91FC17D18F2C6E1937508%40qq.com. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/A7E20597-1DED-4666-BAFA-7F5F79F43A0E%40ix.netcom.com. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/tencent_B33EB1034311F99BC168183BC67393717908%40qq.com.