golang float转string并去除末尾的0

写go时遇到一个场景要求将得到的浮点数保留两位小数,同时要去除末尾的0,试了一下 fmt.Sprintf 和 strconv.FormatFloat 都没能一步到位,最后只能先按小数位约分然后再转成字符串来解决这个问题,如果各位有更好的方式请在评论里指教一下

go 复制代码
package main

import (
	"fmt"
	"math"
	"strconv"
)

func main() {

	var f1 float64 = 9548
	var f2 float64 = 951.200
	var f3 float64 = 95445.12465461315

	fmt.Println("fmt.Sprintf 格式化")
	fmt.Println(fmt.Sprintf("%.2f", f1))
	fmt.Println(fmt.Sprintf("%.2f", f2))
	fmt.Println(fmt.Sprintf("%.2f", f3))

	fmt.Println("strconv.FormatFloat 格式化")
	fmt.Println(strconv.FormatFloat(f1, 'f', 2, 64))
	fmt.Println(strconv.FormatFloat(f1, 'f', -1, 64))
	fmt.Println(strconv.FormatFloat(f2, 'f', -1, 64))
	fmt.Println(strconv.FormatFloat(f3, 'f', -1, 64))

	fmt.Println("round约分后 格式化")
	roundedNum := RoundedNum(f1, 2)
	fmt.Println(strconv.FormatFloat(roundedNum, 'f', -1, 64))
	fmt.Println(strconv.FormatFloat(RoundedNum(f2, 2), 'f', -1, 64))
	fmt.Println(strconv.FormatFloat(RoundedNum(f3, 2), 'f', -1, 64))
}

func RoundedNum(num float64, precision int) float64 {
	roundedNum := math.Round(num*math.Pow10(precision)) / math.Pow10(precision)
	return roundedNum
}
相关推荐
invicinble8 小时前
对linux形成认识
linux·运维·服务器
冷雨夜中漫步8 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
技术路上的探险家8 小时前
8 卡 V100 服务器:基于 vLLM 的 Qwen 大模型高效部署实战
运维·服务器·语言模型
半桔8 小时前
【IO多路转接】高并发服务器实战:Reactor 框架与 Epoll 机制的封装与设计逻辑
linux·运维·服务器·c++·io
绵绵细雨中的乡音8 小时前
深入理解 ET 与 LT 模式及其在 Reactor 模型中的应用
服务器·网络·php
HABuo9 小时前
【linux文件系统】磁盘结构&文件系统详谈
linux·运维·服务器·c语言·c++·ubuntu·centos
Howrun7779 小时前
关于Linux服务器的协作问题
linux·运维·服务器
m0_7369191010 小时前
C++代码风格检查工具
开发语言·c++·算法
2501_9449347310 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
黎雁·泠崖11 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言