iLoveWagons
iLoveWagons

Reputation: 1141

GO: manipulating random generated float64

I was wondering if we can specify to the random generator to how many numbers should be generated after the point decimal?

Example of default behaviour:

fmt.Println(rand.float64())

Would print out the number 0.6046602879796196

Desired behaviour:

fmt.Println(rand.float64(4))

Would then print out the number 0.6047.

Does this functionality already exist in GO or would I have to implement it myself ?

Thank you!

Upvotes: 1

Views: 1089

Answers (2)

nemo
nemo

Reputation: 57757

I don't know of such function, however it is easy to implement by yourself (play):

// Truncate the number x to n decimal places
//
// +- Inf -> +- Inf; NaN -> NaN
func truncate(x float64, n int) float64 {
    return math.Trunc(x * math.Pow(10, float64(n))) * math.Pow(10, -float64(n))
}

Shift the number n decimal places to the left, truncate decimal places, shift the number n places to the right.

In case you want to present your number to the user then you will, at one point, convert the number to a string. When you do that, you should not use this method and instead use string formatting as pointed out by Tyson. For example, as floating point numbers are imprecise there might be rounding errors:

truncate(0.9405090880450124,3) // 0.9400000000000001

Upvotes: 2

Tyson
Tyson

Reputation: 541

It sounds like only the string representation is important to you, and the fmt package does provide that for you:

fmt.Printf("%1.4f", rand.Float64())

So yes, you would still need to wrap this call to specify the number of digits after the decimal point.

func RandomDigits(number int) string {
    return fmt.Sprintf("%1." + strconv.Itoa(number) + "f", rand.Float64())
}

Upvotes: 2

Related Questions