Home  >  Article  >  Backend Development  >  How to convert long range float64 to string in golang

How to convert long range float64 to string in golang

WBOY
WBOYforward
2024-02-09 11:30:09510browse

How to convert long range float64 to string in golang

php editor Apple will introduce to you how to convert a long range of float64 into a string in golang. In golang, the numerical range of float64 type is very wide, but in some cases, we may need to convert it to a string for processing. This article will explain how to use the functions in the strconv package to implement this conversion process through simple examples and code. Whether it is scientific notation or normal number form, we can use this method to convert float64 to string to suit our needs.

Question content

How to convert float 64 value to string. Smaller values ​​are fine, but long ranges are converted to e format, which is not the desired output.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    var mapobj float64
    mapobj = 3856
    fmt.Println(fmt.Sprintf("%v", mapobj))

    var mapobj1 float64
    mapobj1 = 4183856
    fmt64 := strconv.FormatFloat(mapobj1, 'g', -1, 64)
    fmt.Println(fmt.Sprintf("%v", fmt64), fmt64)     <<<< Need to print 4183856
}

Solution

You can do this:

var floatValue float64 = 4183856
println(fmt.Sprintf("%.0f", floatValue)) // will print 4183856

var floatValueWithDecimals float64 = 4183856.6583814
println(fmt.Sprintf("%3f", floatValueWithDecimals)) // will print 4183856.658
    The number between
  • % and f is how many decimal places to print

The above is the detailed content of How to convert long range float64 to string in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete