6

I have 4 float values(startLat, startLon, endLat, endLon) in Go. I want to append (replace) these values to the below string:

var etaString = []byte(`{"start_latitude":"` + startLat + `","start_longitude":"` + startLon + `","end_latitude":"` + endLat + `","end_longitude":"` + endLon }`)

I have to typecast them to string before doing so:

startLat := strconv.FormatFloat(o.Coordinate.Longitude, 'g', 1, 64)

However, when I do so, I get the values of these parameters as:

"4e+01 -1e+02 4e+01 -1e+02"

But I just want something like this: "64.2345".

How can I achieve this?

informatik01
  • 16,038
  • 10
  • 74
  • 104
fnaticRC ggwp
  • 955
  • 1
  • 11
  • 20
  • 1
    `fmt.Sprintf("%.4f", f)` to set a float64 to a string as per a required format. See https://stackoverflow.com/a/62753031/12817546. `strconv.ParseFloat(s, 64)` to set a string to a float64 as per a required format. See https://stackoverflow.com/a/62740786/12817546. –  Jul 09 '20 at 02:04

2 Answers2

12

Package strconv

import "strconv" > func FormatFloat

func FormatFloat(f float64, fmt byte, prec, bitSize int) string

FormatFloat converts the floating-point number f to a string, according to the format fmt and precision prec. It rounds the result assuming that the original was obtained from a floating-point value of bitSize bits (32 for float32, 64 for float64).

The format fmt is one of 'b' (-ddddp±ddd, a binary exponent), 'e' (-d.dddde±dd, a decimal exponent), 'E' (-d.ddddE±dd, a decimal exponent), 'f' (-ddd.dddd, no exponent), 'g' ('e' for large exponents, 'f' otherwise), or 'G' ('E' for large exponents, 'f' otherwise).

The precision prec controls the number of digits (excluding the exponent) printed by the 'e', 'E', 'f', 'g', and 'G' formats. For 'e', 'E', and 'f' it is the number of digits after the decimal point. For 'g' and 'G' it is the total number of digits. The special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly.

Use a precision of -1, not 1. Use a format of f, not g to avoid exponent form for large exponents (see HectorJ's comment).

startLat := strconv.FormatFloat(o.Coordinate.Longitude, 'f', -1, 64)

For example,

package main

import (
    "fmt"
    "strconv"
)

func main() {
    f := 64.2345
    s := strconv.FormatFloat(f, 'g', 1, 64)
    fmt.Println(s)
    s = strconv.FormatFloat(f, 'f', -1, 64)
    fmt.Println(s)
}

Output:

6e+01
64.2345
Community
  • 1
  • 1
peterSO
  • 158,998
  • 31
  • 281
  • 276
0

Some other options:

package main
import "fmt"

func main() {
   n := 64.2345
   { // example 1
      s := fmt.Sprint(n)
      fmt.Println(s == "64.2345")
   }
   { // example 2
      s := fmt.Sprintf("%v", n)
      fmt.Println(s == "64.2345")
   }
   { // example 3
      s := fmt.Sprintf("%g", n)
      fmt.Println(s == "64.2345")
   }
}
Zombo
  • 1
  • 62
  • 391
  • 407