Home > Mobile >  Go - multiple by scientific notation
Go - multiple by scientific notation

Time:09-06

I'm looking for an example of how to calculate 1 * 10 ^ x in golang.

For example 1 * 10 ^ 18 gives me the output of 24 instead of 1000000000000000000

essentially I'd like to be able to perform x * 1e{y}

CodePudding user response:

In GoLang ^ is used for bitwise XOR.

You can learn about GoLang operators from here. GoLang Operators

You can perform the above operation using the math in GoLang.

package main

import (
    "fmt"
    "math"
)

func main() {
    x := 1.0
    res := x * math.Pow(10, 18)
    fmt.Printf("%f", res)
}

CodePudding user response:

I think other answers have already pointed this out, but ^ is bitwise XOR. When you do 1 * 10 ^ 18, you're essentially evaluating 10 ^ 18. Since, 10 evaluates to 01010 in binary and 18 evaluates to 10010 in binary, 10 ^ 18 would result in 11000 or 24.

To get the result you want, you should do:

package main

import (
    "fmt"
    "math"
)

func main() {
    multiplier := 1.0
    exponent := 18
    result := multiplier * math.Pow10(exponent)
    fmt.Printf("%f * 10 ^ %d = %f", multiplier, exponent, result)
}

In this example, the work is being done by the Pow10 function in the math package. It produces a value equal to ten to the power of the value given to the function. Then we multiply this by the multiplier to get the result. Running this code would yield the following:

1.000000 * 10 ^ 18 = 1000000000000000000.000000
  •  Tags:  
  • go
  • Related