how to force to save all decimal points of bigFloat in file, instead of rounding

Viewed 63

Let's assume I have a very accurate input number(string format), and after math/big manipulation, I want to convert to string format again.

package main

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

func check(e error) {
    if e != nil {
        panic(e)
    }
}


func main() {   
    // edit
    s := "3.1415926123456789123456789123456789123456789"
    var n, _ = new(big.Float).SetString(s)
    // var n = big.NewFloat(3.1415926123456789123456789123456789123456789)
    fmt.Println(n) // 3.1415926123456788 

    N := n.String()
    fmt.Println(N)  // 3.141592612

    d1 := []byte(N)
    err := os.WriteFile("./dat1.txt", d1, 0644) // 3.141592612
    check(err)
}

How to save a big Float like 3.1415926123456789123456789123456789123456789 into a file? I want to keep all the decimal points, or at least as much as possible

2 Answers

You can parse and store your input "precisely", but you must increase the precision (the default precision doesn't cover that). Use Float.SetPrec() for that (requires a bit-count).

When generating text representation, use Float.Text(), again, with sufficiently large precision (requires a decimal digit-count). If you don't know the required digit-precision, as per the doc, you may use a negative value to have the smallest number of decimal digits that is needed for the Float's mantissa bits.

For example:

s := "3.1415926123456789123456789123456789123456789"
fmt.Println(s)

n := big.NewFloat(0)
n.SetPrec(200)
n.SetString(s)

N := n.Text('f', 50)
fmt.Println(N)

N = n.Text('f', -1)
fmt.Println(N)

This will output (try it on the Go Playground):

3.1415926123456789123456789123456789123456789
3.14159261234567891234567891234567891234567890000000
3.1415926123456789123456789123456789123456789

I've just looked what String method does and its documentation (https://pkg.go.dev/math/big#Float.String).

String formats x like x.Text('g', 10)...

So let's go to that method doc.

func (x *Float) Text(format byte, prec int) string

Text converts the floating-point number x to a string according to the given format and precision prec.

The precision prec controls the number of digits ... A negative precision selects the smallest number of decimal digits necessary to identify the value x uniquely

All you need is just reading the doc.

Related