Convert float to string according to the required format.

I have 4 float values โ€‹โ€‹(startLat, startLon, endLat, endLon) in go. I want to add (replace) these values โ€‹โ€‹below the line:

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

I have to cast them to a string before doing this.

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

However, when I do this, 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? TIA :)

+4
source share
1 answer

Strconv package

import "strconv"> func FormatFloat

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

FormatFloat f , fmt . , (32 float32, 64 float64).

fmt "b" (-ddddp ยฑ ddd, ), 'e' (-d.dddde ยฑ dd, ), 'E' (-d.ddddE ยฑ dd, ), 'f' (-ddd.dddd, ), 'g' ('e' , 'f' ), 'G' ('E' , 'f' ).

( ), 'e', โ€‹โ€‹'E', 'f', 'g' 'G'. "e", 'E', 'f' - . 'g' 'G' - . -1 , ParseFloat f .

-1, 1. f, g, (. HectorJ).

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

,

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)
}

:

6e+01
64.2345
+3

Source: https://habr.com/ru/post/1616918/


All Articles