douaikuai2715 2015-11-22 06:03
浏览 76
已采纳

按照要求的格式将float转换为go lang中的字符串。

I have 4 float values(startLat,startLon,endLat,endLon)in go . I want to append(replace) these values to 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 ? TIA :)

  • 写回答

1条回答 默认 最新

  • 普通网友 2015-11-22 06:11
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常