当前位置:网站首页>Judging decimal points and rounding of decimal operations in Golang
Judging decimal points and rounding of decimal operations in Golang
2022-07-31 21:35:00 【m0_67401228】
Decimal point and rounding in Golang decimal operation
Golang is easy to learn
Article Directory
- Golang decimal operation to determine the number of decimal points and rounding
- I. Determine the number of decimal points
- Two, round off
- Summary
I. Determine how many decimal points
1. Determine how many decimal points
Load the cast package
go get github.com/spf13/cast
The code is as follows (example):
package mainimport ("fmt""github.com/spf13/cast""math""regexp""strconv")func main() {num1 := 5.335// Determine how many decimalsdecimal, _ := CheckDecimal(cast.ToString(num1), "2")fmt.Println(decimal)}// CheckDecimal determines the number of decimal points after the decimal point// str is the decimal string to be judged// n is the number of digits to be judgedfunc CheckDecimal(str string, n string) (bool, error) {// regular comparison via regexp// ([1-9]d*) any number of digits 1-9// (0) or the first bit is 0// d{0,`+n+`} 0-n digitsreturn regexp.MatchString(`^(([1-9]d*)|(0))(.d{0,`+n+`})?$`, str)}Two, rounded up
1.fmt.Sprintf
Test:
5.334
5.335
5.336
The code is as follows (example):
package mainimport ("fmt""github.com/spf13/cast""math""strconv")func main() {num1 := 5.334fmt.Println(Float64Rand(num1,2))}//roundingfunc Float64Rand(v float64, dig int) float64 {cDig := strconv.Itoa(dig)val := fmt.Sprintf("%0."+cDig+"f", v)return cast.ToFloat64(val)}Results

From the results, we can know that the rounding function of the official package fmtCan't meet our perfect expectations, rounding can be done, but the five-in fails, it only takes effect when the third becomes a six
2.math.Round(result*pow)
Test:
5.334
5.335
5.336
The code is as follows (example):
package mainimport ("fmt""github.com/spf13/cast""math""strconv")func main() {num1 := 5.334fmt.Println("num1:",num1)fmt.Println("res1:",FormatFloat(num1,2))num2 := 5.335fmt.Println("num2:",num2)fmt.Println("res2:",FormatFloat(num2,2))num3 := 5.336fmt.Println("num3:",num3)fmt.Println("res3:",FormatFloat(num3,2))}func FormatFloat(f float64, dig int) float64 {result := cast.ToFloat64(strconv.FormatFloat(f, 'f', dig+1, 64))pow := math.Pow(10, float64(dig))return math.Round(result*pow) / pow}Results

From the result, math.Round(result*pow) to our perfect expectations, rounding can be done.
Summary
When the official package is not enough to meet our needs, we need to find a method that can meet our needs to achieve the desired function, and we will try to round up through the official package in the future, so that we can expand our knowledge.
Hope this blog will be useful to you.I am the King of Light, and I speak for myself.
Let me introduce myself first. The editor graduated from Shanghai Jiaotong University in 2013. I worked in a small company and went to big factories such as Huawei and OPPO. I joined Alibaba in 2018, until now.I know that most junior and intermediate java engineers want to upgrade their skills, they often need to explore their own growth or sign up to study, but for training institutions, the tuition fee is nearly 10,000 yuan, which is really stressful.Self-learning that is not systematic is very inefficient and lengthy, and it is easy to hit the ceiling and the technology stops.Therefore, I collected a "full set of learning materials for java development" for everyone. The original intention is also very simple. I hope to help friends who want to learn by themselves but don't know where to start, and at the same time reduce everyone's burden.Add the business card below to get a full set of learning materials
边栏推荐
- Implementation of a sequence table
- uni-app中的renderjs使用
- Linux environment redis cluster to build "recommended collection"
- 广汽本田安全体验营:“危险”是最好的老师
- What's wrong with the sql syntax in my sql
- Several methods of mysql backup table
- Mobile web development 02
- Carbon教程之 基本语法入门大全 (教程)
- Performance optimization: remember a tree search interface optimization idea
- 老牌音乐播放器 WinAmp 发布 5.9 RC1 版:迁移到 VS 2019 完全重建,兼容 Win11
猜你喜欢
![[Open class preview]: Research and application of super-resolution technology in the field of video image quality enhancement](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[Open class preview]: Research and application of super-resolution technology in the field of video image quality enhancement
![[NLP] What is the memory of the model!](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[NLP] What is the memory of the model!

【论文精读】iNeRF

GAC Honda Safety Experience Camp: "Danger" is the best teacher

Socket回顾与I/0模型

Introduction to Audio Types and Encoding Formats in Unity

Financial profitability and solvency indicators
![leetcode: 6135. The longest ring in the graph [inward base ring tree + longest ring board + timestamp]](/img/91/284de3dcbb8d143d85775b314dd41c.png)
leetcode: 6135. The longest ring in the graph [inward base ring tree + longest ring board + timestamp]

顺序表的实现

Go1.18 upgrade function - Fuzz test from scratch in Go language
随机推荐
【Yugong Series】July 2022 Go Teaching Course 023-List of Go Containers
Chapter Six
multithreaded lock
How to change npm to Taobao mirror [easy to understand]
Short-circuit characteristics and protection of SiC MOSFETs
matplotlib ax bar color Set the color, transparency, label legend of the ax bar
GAC Honda Safety Experience Camp: "Danger" is the best teacher
Made with Flutter and Firebase!counter application
Count characters in UTF-8 string function
idea中搜索具体的字符内容的快捷方式
关注!海泰方圆加入《个人信息保护自律公约》
Transfer Learning - Domain Adaptation
Several methods of mysql backup table
leetcode: 6135. The longest ring in the graph [inward base ring tree + longest ring board + timestamp]
[Open class preview]: Research and application of super-resolution technology in the field of video image quality enhancement
Shell 脚本 快速入门到实战 -02
How can we improve the real yourself, become an excellent architect?
Istio introduction
请问我的这段sql中sql语法哪里出了错
角色妆容的实现