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

How to convert long range float64 to string in golang

WBOY
Release: 2024-02-09 11:30:09
forward
603 people have browsed it

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
}
Copy after login

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
Copy after login
    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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template