当前位置:网站首页>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
边栏推荐
- ECCV 2022 Huake & ETH propose OSFormer, the first one-stage Transformer framework for camouflaging instance segmentation!The code is open source!...
- 架构实战营模块 8 作业
- Chapter VII
- How to get useragent
- Batch (batch size, full batch, mini batch, online learning), iterations and epochs in deep learning
- 【AcWing】第 62 场周赛 【2022.07.30】
- 高通cDSP简单编程例子(实现查询高通cDSP使用率、签名),RK3588 npu使用率查询
- 全网一触即发,自媒体人的内容分发全能助手——融媒宝
- -xms -xmx(information value)
- BM3 flips the nodes in the linked list in groups of k
猜你喜欢
Tkinter 入门之旅
Bika LIMS open source LIMS set - use of SENAITE (detection process)
Efficient Concurrency: A Detailed Explanation of Synchornized's Lock Optimization
架构实战营模块八作业
Go mode tidy reports an error go warning “all” matched no packages
第七章
Go1.18 upgrade function - Fuzz test from scratch in Go language
How programmers learn open source projects, this article tells you
关注!海泰方圆加入《个人信息保护自律公约》
Teach you how to deploy Nestjs projects
随机推荐
Shell 脚本 快速入门到实战 -02
[Code Hoof Set Novice Village 600 Questions] Merge two numbers without passing a character array
Basic configuration of OSPFv3
Redis Overview: Talk to the interviewer all night long about Redis caching, persistence, elimination mechanism, sentinel, and the underlying principles of clusters!...
One thing to say, is outsourcing company worth it?
每月一书(202207):《Swift编程权威指南》
顺序表的实现
Redis综述篇:与面试官彻夜长谈Redis缓存、持久化、淘汰机制、哨兵、集群底层原理!...
20. Support vector machine - knowledge of mathematical principles
21. Support Vector Machine - Introduction to Kernel Functions
Mobile web development 02
rj45 to the connector Gigabit (Fast Ethernet interface definition)
Linux environment redis cluster to build "recommended collection"
MATLAB program design and application 2.4 Common internal functions of MATLAB
NVIDIA has begun testing graphics products with AD106 and AD107 GPU cores
性能优化:记一次树的搜索接口优化思路
使用 Flutter 和 Firebase 制作!计数器应用程序
给定一个ip地址,子网掩码怎么算网络号(如何获取ip地址和子网掩码)
sqlite3简单操作
sqlite3 simple operation