This question already has an answer here:
Golang Round to Nearest 0.05
(1 answer)
Closed 4 years ago.
I want to trim latitude and longitude of address upto 5 decimal points.
latitude and longitude are of type float64 I have created a function round the value.
My function is like this::
func DoubleRoundFive(val float64) float64 {
formattedVal := fmt.Sprintf("%.5f", val)
roundedVal, _ := strconv.ParseFloat(formattedVal, 64)
return roundedVal
}
Output and usage::
DoubleRoundFive(76.70289609999999)
Output::
76.7029
But I just want to trim the value upto 5 decimal points. I want output as 76.70289 . Is it possible in GO??
I want exact 5 decimal values because I am using this for latitude longitude.
This is a GO playground Link
Try this:
package main
import (
"fmt"
)
func main() {
val := DoubleRoundFive(76.70289609999999)
fmt.Println(val)
}
func DoubleRoundFive(val float64) float64 {
valInt := int64(val*100000)
val = float64(valInt)/100000
return val
}
Go Playground: https://play.golang.org/p/O_H_buvJtDO
Related
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
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.
This question already has an answer here:
How to perform division in Go
(1 answer)
Closed 1 year ago.
Why doesn't my float64 have any decimal points?
I expected 40000/3 should return something like 13333.3333
package main
import (
"fmt"
)
func main() {
var f float64 = 40000 / 3
fmt.Println(f)
}
https://play.golang.org/p/OxjLjwPGYhx
40000/3 is an integer value. It is then converted to a float. To perform float division use float values. 40000.0/3 will result in a float value.
This question already has answers here:
How to generate a random string of a fixed length in Go?
(18 answers)
Closed 4 years ago.
I would like to generate number for invitation code.
I get a number of digit for this and i need to generate a string number according to this digit.
Example :
For 3 i need to generate a string number beetween 111 and 999
for 4 1111 to 9999
for 2 11 to 99
etc...
What is the best way to do that ?
I have some idea like making two empty string filling them with 1 for the first one according to x, with 9 for the second one according to X.
Then converting them to int and make a random between these two number, but i don't thik it's the optimal way to do it.
package main
import (
"fmt"
"math/rand"
"strconv"
"time"
)
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
func main() {
x := 3
first := ""
second := ""
i := 0
for i < x {
first = first + "1"
i = i + 1
}
i = 0
for i < x {
second = second + "9"
i = i + 1
}
rand.Seed(time.Now().UTC().UnixNano())
fmt.Println(first)
fmt.Println(second)
firstInt, _ := strconv.Atoi(first)
secondInt, _ := strconv.Atoi(second)
fmt.Println(randInt(firstInt, secondInt))
}
regards
You can do something like this:
package main
import (
"fmt"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
var numbers = []rune("0123456789")
func GenerateNumberString(length int) string {
b := make([]rune, length)
for i := range b {
b[i] = numbers[rand.Intn(len(numbers))]
}
return string(b)
}
func main() {
fmt.Println(GenerateNumberString(2))
fmt.Println(GenerateNumberString(3))
fmt.Println(GenerateNumberString(4))
}
Try it here in the go playground.
I have the following:
package main
import (
"fmt"
"math"
)
func main() {
nums := []float64{
0.15807659924030304, 0.10901273787021637, 0.04955724626779556, 0.05886702239513397,
}
for _, f := range nums {
fmt.Println(f, math.Round(f/.0001)*.0001)
}
}
output is:
0.15807659924030304 0.15810000000000002
0.10901273787021637 0.109
0.04955724626779556 0.049600000000000005
0.05886702239513397 0.0589
Why are some ending up with > 4 decimal places? How do I correct it?
https://play.golang.org/p/kLvVjmsjq6Y
fmt.Printf("%f %b %0.4f\n", f, f, math.Round(f/.0001)*.0001)
Try using that. The %0.4f will format it to 4 decimal places. In fact if you only need the string, use that instead of your Round function.
The %b will show you the real value. In Go that will display a large decimal (base-10) value, a p, then the exponent in powers of 2. So when it displays 5695309707476992p-55 you can find the floating point by doing 5695309707476992 / 2^55
When printing out some values from a map of structs. I see certain float64 values with alternative notation. The test passes but how do you read this notation (4e-06). Is this value indeed the same as "0.000004"?
package main
import (
"fmt"
"strconv"
"testing"
)
func TestXxx(t *testing.T) {
num := fmt.Sprintf("%f", float64(1.225788)-float64(1.225784)) // 0.000004
f, _ := strconv.ParseFloat(num, 64)
if f == 0.000004 {
t.Log("Success")
} else {
t.Error("Not Equal", num)
}
if getFloat(f) == 0.000004 {
t.Log("Success")
}else{
t.Error("Fail", getFloat(f))
}
}
func getFloat(f float64) float64 {
fmt.Println("My Float:",f) // 4e-06
return f
}
The notation is called Scientific notation, and it is a convenient way to print very small or very large numbers in compact, short form.
It has the form of
m × 10n
(m times ten raised to the power of n)
In programming languages it is written / printed as:
men
See Spec: Floating-point literals.
Your number: 4e-06, where m=4 and n=-6, which means 4*10-6 which equals to 0.000004.
In order to print your floats in a regular way you can do something like this example:
package main
import (
"fmt"
"strconv"
)
func main() {
a, _ := strconv.ParseFloat("0.000004", 64)
b, _ := strconv.ParseFloat("0.0000000004", 64)
c := fmt.Sprintf("10.0004")
cc, _ := strconv.ParseFloat(c, 64)
fmt.Printf("%.6f\n", a) // 6 numbers after the point
fmt.Printf("%.10f\n", b) // 10 numbers afer the point
fmt.Printf("%.4f\n", cc) // 4 numbers after the point
}
Output:
0.000004
0.0000000004
10.0004
It is the same number. You can use fmt.Printf("My Float: %.6f\n",f) if you don't like the scientific notation. (This format requests that 6 digits will be printed after the decimal point.)