Solve the accuracy problem of addition, subtraction, multiplication and division of Golang decimal float64 in actual projects

The float64 type of GO language will have some problems when doing addition, subtraction, multiplication and division For example, multiplication operations, examples, convert decimal units into integer points: It was found that after multiplying the decimal yuan by 100 and forcing it to be converted into an integer cent, 1 cent was missing Solution: var ( a, b float64 c int64 ) a = 2.55 b = 0.0 c = int64((a + b) * 100.0) fmt.Printf(“The 1st time c=%d\n”, c) //The 1st time c=254 c = int64(a * 100.0) fmt.Printf(“The 2nd time c=%d\n”, c) //The 2nd time c=254 fmt.Println(a * 100) //254.99999999999997 //It is found that after multiplying the decimal yuan by 100 and forcing it to be converted into an integer cent, 1 cent is missing. //Solution 1: tmpStr1 := fmt.Sprintf(“%.2f”, a) tmpStr2 := fmt.Sprintf(“%.2f”, b) tmpnum1, _ := strconv.ParseInt(strings.Replace(tmpStr1, “.”, “”, 1), 10, 64) tmpnum2, _ := strconv.ParseInt(strings.Replace(tmpStr2, “.”, “”, 1), 10, 64) c = tmpnum1 + tmpnum2 fmt.Printf(“The third time c=%d\n”, c) //The third time c=255 //Method 2: num3 := math.Ceil(a * 100.0) fmt.Printf(“num3=%d\n”, int64(num3)) //num3=255 //Method 3: strFloat := strconv.FormatFloat(a*100, ‘f’, 0, 64) nInt64, err := strconv.ParseInt(strFloat, 10, 64) Supplement: golang float64, in64 mutual conversion precision…

JavaScript solution to the problem of loss of precision in addition, subtraction, multiplication and division of decimals

Reason: js handles the addition, subtraction, multiplication and division of decimals according to the binary system. On the basis of arg1, the precision of arg2 is expanded or inversely expanded to match, so the following situation will occur. The problem of decimal point addition, subtraction, multiplication and division in Javascript (js) is a js bug, such as 0.3*1 = 0.2999999999, etc. Listed below are four js algorithms that can perfectly obtain the corresponding accuracy function accDiv(arg1,arg2){ var t1=0,t2=0,r1,r2; try{t1=arg1.toString().split(“.”)[1].length}catch(e){} try{t2=arg2.toString().split(“.”)[1].length}catch(e){} with(Math){ r1=Number(arg1.toString().replace(“.”,””)) r2=Number(arg2.toString().replace(“.”,””)) return accMul((r1/r2),pow(10,t2-t1)); } } //Multiplication function accMul(arg1,arg2) { var m=0,s1=arg1.toString(),s2=arg2.toString(); try{m+=s1.split(“.”)[1].length}catch(e){} try{m+=s2.split(“.”)[1].length}catch(e){} return Number(s1.replace(“.”,””))*Number(s2.replace(“.”,””))/Math.pow(10,m) } //addition function accAdd(arg1,arg2){ var r1,r2,m; try{r1=arg1.toString().split(“.”)[1].length}catch(e){r1=0} try{r2=arg2.toString().split(“.”)[1].length}catch(e){r2=0} m=Math.pow(10,Math.max(r1,r2)) return (arg1*m+arg2*m)/m } //Subtraction function Subtr(arg1,arg2){ var r1,r2,m,n; try{r1=arg1.toString().split(“.”)[1].length}catch(e){r1=0} try{r2=arg2.toString().split(“.”)[1].length}catch(e){r2=0} m=Math.pow(10,Math.max(r1,r2)); n=(r1>=r2)?r1:r2; return ((arg1*m-arg2*m)/m).toFixed(n); } Let’s analyze the problem of loss of numerical precision in Javascript 1. Some typical problems with JS digital precision loss 1. Add two simple floating point numbers 0.1 + 0.2 != 0.3 // true Firebug This is really not a Firebug problem, you can try using alert (haha, just kidding). Look at the results of Java operations Look at Python again 2. Large integer operations 9999999999999999 == 10000000000000001 // ? Firebug It makes no sense that the 16-digit and…

Sample code for applying addition, subtraction, comparison, and format conversion to js time function_javascript skills

The code is as follows: // Javascript Document //—- ———————————————– // Determine leap year//—————————————– ———- Date.prototype.isLeapYear = function() { return (0==this.getYear()%4&&((this.getYear()%100!=0 )||(this.getYear()%400==0))); } //——————– ———————————- // Date formatting// Format YYYY/yyyy/YY /yy represents year// MM/M month// W/w week// dd/DD/d/D date// hh/HH/h/H time >// mm/m minutes// ss/SS/s/S seconds//———————— ————————– // Extension of Date, convert Date into String in specified format // Month (M), day (d), hour (h), minute (m), second (s), quarter (q) can use 1-2 placeholders, // year (y) can use 1 -4 placeholders, milliseconds (S) can only use 1 placeholder (a number with 1-3 digits) // Example: // (new Date()).Format(” yyyy-MM-dd hh:mm:ss.S”) ==> 2006-07-02 08:09:04.423 // (new Date()).Format(“yyyy-M-d h:m:s.S “) ==> 2006-7-2 8:9:4.18 Date.prototype.Format = function(fmt) { //author: meizz var o = { “M+” : this.getMonth()+1, //month“d+” : this.getDate(), //day“h+” : this.getHours(), //hour“H+” : this.getHours(), //Hours“m+” : this.getMinutes(), //Minutes“s+” : this.getSeconds(), //Seconds“q+” : Math .floor((this.getMonth()+3)/3), //Quarter“S” : this.getMilliseconds() //Milliseconds}; if(/(y+)/. test(fmt)) fmt=fmt.replace(RegExp.$1, (this.getFullYear()+””).substr(4 – RegExp.$1.length)); for(var k in o ) if(new RegExp(“(“+ k +”)”).test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? ( o[k]) : ((“00″+ o[k]).substr((“”+ o[k]).length))); return fmt; } /** * Extension of Date, convert Date into String in specified format * Month (M), day (d), 12 hours (h), 24 hours…

Precise calculation of js floating point numbers (addition, subtraction, multiplication, division)_javascript skills

The code is as follows: / /Note: The addition result of Javascript will have errors, which will be more obvious when adding two floating point numbers. This function returns a more accurate addition result. //Call: accAdd(arg1,arg2) //Return value: the exact result of arg1 plus arg2function accAdd(arg1,arg2){ var r1,r2,m; try{r1=arg1.toString().split(“.”)[1].length}catch(e){r1=0} try{r2=arg2.toString().split(“. “)[1].length}catch(e){r2=0} m=Math.pow(10,Math.max(r1,r2)) return (arg1*m+arg2*m) /m } The code is as follows: //Description: There will be an error in the subtraction result of Javascript. Between two floating point numbers It will be more obvious when added together. This function returns a more accurate subtraction result. //Call: accSub(arg1,arg2) //Return value: the exact result of arg1 minus arg2function accSub(arg1,arg2){ return accAdd(arg1,-arg2) ; } The code is as follows: //Description: The multiplication result of Javascript will have errors. When two floating point numbers are compared, It will be more obvious when multiplying. This function returns a more accurate multiplication result. //Call: accMul(arg1,arg2) //Return value: the exact result of arg1 multiplied by arg2function accMul(arg1,arg2) { var m=0, s1=arg1.toString(),s2=arg2.toString(); try{m+=s1.split(“.”)[1].length}catch(e){} try{m+= s2.split(“.”)[1].length}catch(e){} return Number(s1.replace(“.”,””))*Number(s2.replace(“.”,” “))/Math.pow(10,m) } The code is as follows: //Description: Javascript division The result will have errors, which will be more obvious when dividing two floating point numbers. This function returns a more accurate…

Solution to the loss of precision problem in js addition, subtraction, multiplication and division_javascript skills

In Javascript, when you use decimals for addition, subtraction, multiplication and division, you will find that the results are sometimes followed by a long period of decimals, which complicates the operation and affects the calculation results. I checked the reasons online and found the following: In Javascript, many decimal places will always appear when calculating data with decimals. This is because the calculation of floating point numbers in Javascript is based on binary calculations. The code is as follows: /* * * Addition operation to avoid multiple digits and loss of calculation accuracy after the decimal point is added to the data. * * @param num1 addend 1 | num2 addend 2 */ function numAdd(num1, num2) { var baseNum, baseNum1, baseNum2; try { baseNum1 = num1.toString().split(“.”)[1].length; } catch (e) { baseNum1 = 0; } try { baseNum2 = num2.toString().split(“.”)[1].length; } catch (e) { baseNum2 = 0; } baseNum = Math.pow( 10, Math.max(baseNum1, baseNum2)); return (num1 * baseNum + num2 * baseNum) / baseNum; }; /** * Addition operation to avoid data subtraction Multiple digits are produced after the decimal point and calculation accuracy is lost. * * @param num1 minuend | num2 minuend*/ function numSub(num1, num2) { var baseNum, baseNum1,…

Precise calculation of js floating point numbers (addition, subtraction, multiplication, division)_javascript skills

The code is as follows: / /Note: The addition result of Javascript will have errors, which will be more obvious when adding two floating point numbers. This function returns a more accurate addition result. //Call: accAdd(arg1,arg2) //Return value: the exact result of arg1 plus arg2function accAdd(arg1,arg2){ var r1,r2,m; try{r1=arg1.toString().split(“.”)[1].length}catch(e){r1=0} try{r2=arg2.toString().split(“. “)[1].length}catch(e){r2=0} m=Math.pow(10,Math.max(r1,r2)) return (arg1*m+arg2*m) /m } The code is as follows: //Description: There will be an error in the subtraction result of Javascript. Between two floating point numbers It will be more obvious when added together. This function returns a more accurate subtraction result. //Call: accSub(arg1,arg2) //Return value: the exact result of arg1 minus arg2function accSub(arg1,arg2){ return accAdd(arg1,-arg2) ; } The code is as follows: //Description: The multiplication result of Javascript will have errors. When two floating point numbers are compared, It will be more obvious when multiplying. This function returns a more accurate multiplication result. //Call: accMul(arg1,arg2) //Return value: the exact result of arg1 multiplied by arg2function accMul(arg1,arg2) { var m=0, s1=arg1.toString(),s2=arg2.toString(); try{m+=s1.split(“.”)[1].length}catch(e){} try{m+= s2.split(“.”)[1].length}catch(e){} return Number(s1.replace(“.”,””))*Number(s2.replace(“.”,” “))/Math.pow(10,m) } The code is as follows: //Description: Javascript division The result will have errors, which will be more obvious when dividing two floating point numbers. This function returns a more accurate…

Solution to the loss of precision problem in js addition, subtraction, multiplication and division_javascript skills

In Javascript, when you use decimals for addition, subtraction, multiplication and division, you will find that the results are sometimes followed by a long period of decimals, which complicates the operation and affects the calculation results. I checked the reasons online and found the following: In Javascript, many decimal places will always appear when calculating data with decimals. This is because the calculation of floating point numbers in Javascript is based on binary calculations. The code is as follows: /* * * Addition operation to avoid multiple digits and loss of calculation accuracy after the decimal point is added to the data. * * @param num1 addend 1 | num2 addend 2 */ function numAdd(num1, num2) { var baseNum, baseNum1, baseNum2; try { baseNum1 = num1.toString().split(“.”)[1].length; } catch (e) { baseNum1 = 0; } try { baseNum2 = num2.toString().split(“.”)[1].length; } catch (e) { baseNum2 = 0; } baseNum = Math.pow( 10, Math.max(baseNum1, baseNum2)); return (num1 * baseNum + num2 * baseNum) / baseNum; }; /** * Addition operation to avoid data subtraction Multiple digits are produced after the decimal point and calculation accuracy is lost. * * @param num1 minuend | num2 minuend*/ function numSub(num1, num2) { var baseNum, baseNum1,…

Simple example of addition, subtraction, multiplication and division in javascript

A simple example of Javascript addition, subtraction, multiplication and division accDiv: accMul: accAdd: accSubtr: The above simple example of Javascript addition, subtraction, multiplication and division is all the content shared by the editor. I hope it can give you a reference and I hope you will support it.

Addition, subtraction, multiplication, division, size comparison and usage precautions of BigDecimal in Java

Foreword To borrow words from the book “Effactive Java”, the main design goals of the float and double types are for scientific computing and engineering calculations. They perform binary floating-point operations, which are carefully designed to provide fast approximate calculations with high accuracy over a wide range of values. However, they do not provide completely accurate results and should not be used where accurate results are required. However, business calculations often require accurate results. In Java, the maximum value of int is: 2147483647. Now what if you want to use a number larger than this? In other words, the value is larger, so BigDecimal is used. There are many introductions to BigDecimal. Friends who need to know more can refer to this article: https://www.jb51.net/article/55395.htm 1. Addition, subtraction, multiplication and division of BigDecimal BigDecimal bignum1 = new BigDecimal(“10”); BigDecimal bignum2 = new BigDecimal(“5”); BigDecimal bignum3 = null; //addition bignum3 = bignum1.add(bignum2); System.out.println(“sum is: ” + bignum3); //Subtraction bignum3 = bignum1.subtract(bignum2); System.out.println(“The difference is: ” + bignum3); //Multiplication bignum3 = bignum1.multiply(bignum2); System.out.println(“The product is: ” + bignum3); //division bignum3 = bignum1.divide(bignum2); System.out.println(“Business is: ” + bignum3); The running result is: 2. Comparative size of BigDecimal. BigDecimal num1 = new BigDecimal(“0”); BigDecimal num2…

[Java] BigDecimal implements code for addition, subtraction, multiplication and division operations

java.math.BigDecimal BigDecimal has a total of 4 ways to create it. Let me take a look at two of them first: The first type: BigDecimal(double val) Translates a double into a BigDecimal. Second type: BigDecimal(String val) Translates the String repre sentation of a BigDecimal into a BigDecimal. To use BigDecimal, you need to use String to create it. To do an addition operation, you need to convert two floating point numbers to String first, and then create a BigDecimal. Call the add method on one of them, pass in the other as a parameter, and then Convert the result of the operation (BigDecimal) to a floating point number. public static double add(double v1,double v2) public static double sub(double v1,double v2) public static double mul(double v1,double v2) public static double div(double v1,double v2) public static double div(double v1,double v2,int scale) public static double round(double v,int scale) Tool class: Arith /** * Since Java’s simple types cannot perform precise operations on floating-point numbers, this utility class provides precise floating-point operations, including addition, subtraction, multiplication, division, and rounding. */ public class Arith { //Default division operation precision private static final int DEF_DIV_SCALE = 10; // This class cannot be instantiated private Arith() {…

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索