Introduction
Effective Java 2nd Edition Recommendation 48th: Avoid using float and doble if you need precise answers. float and double types are primarily designed for scientific calculations and engineering calculations. They perform binary floating point arithmetic (binary floating-point arithmetic), which is designed to provide more accurate, fast approximation calculations over a wide range of values. However, they do not provide completely accurate results, so they should not be used in situations where precise results are required. The float and double types are especially unsuitable for currency calculations because it is not possible to have a float or double that accurately represent 0.1 (or any other negative number of 10). The correct way to solve this problem is to use BigDecimal, int, or long for currency calculations.
1. Why float and double are approximate calculations
float and double cannot be calculated precisely by their design. For more information, please refer to the following blog post:
Why is the Java float double precision lost? On the accuracy of floating-point numbers in Java
2. Use long for accurate calculations
This example implements the use of a long type to complete the precise addition and subtraction of floating-point numbers, because the division itself is not divisible by many, so the exact calculation of the division did not think of a good method.
Since long has a range of -2^63-–2^63-1, that is, decimal: -9223372036854775808-–9223372036854775807
Therefore, it is necessary to ensure that the calculation result and the intermediate result do not exceed the range of long for accurate calculation using long. For larger numbers, use BigDecimal.
On the code:
PackageEffectivejava.chapter8;ImportJava.math.BigDecimal;/** * * This example implements the use of a long type to complete the precise addition and subtraction of floating-point numbers, because the division itself is not divisible by many, so the exact calculation of the division did not think of a good method. * Because long is represented by -2^63-----2^63-1, that is, decimal: -9223372036854775808-----9223372036854775807 * Therefore, it is necessary to ensure that the calculation result and the intermediate result do not exceed the range of long for accurate calculation using long. For larger numbers, use BigDecimal. */ Public class exactcomputationbylong { /** * 1. Gets the long and moving digits of two decimal places after the right shift of the decimal point; 2. The unified mobile number is two of the largest, 3. add; 4. Move the decimal point to the left of the added number. */ Public StaticStringAdd(String stra, String StrB) {Exactlong Exacta =NewExactlong (Stra); Exactlong EXACTB =NewExactlong (StrB);intMaxscale = Getmaxscale (Exacta, EXACTB); Changesacle (Exacta, Maxscale); Changesacle (EXACTB, Maxscale);LongAddnum = Exacta.getdata () + exactb.getdata (); String resultinit = Getdatafromlong (Addnum, Maxscale);returnGetresultwithzero (Resultinit); }/** * process is the same as addition. */ Public StaticStringSubtract(String stra, String StrB) {Exactlong Exacta =NewExactlong (Stra); Exactlong EXACTB =NewExactlong (StrB);intMaxscale = Getmaxscale (Exacta, EXACTB); Changesacle (Exacta, Maxscale); Changesacle (EXACTB, Maxscale);LongSubnum = Exacta.getdata ()-Exactb.getdata (); String resultinit = Getdatafromlong (Subnum, Maxscale);returnGetresultwithzero (Resultinit); }/** * process is similar to addition, the only difference is that the number of moving bits is Maxscale * 2. */ Public StaticStringMultiply(String stra, String StrB) {Exactlong Exacta =NewExactlong (Stra); Exactlong EXACTB =NewExactlong (StrB);if(Exacta.getdata () = =0|| Exactb.getdata () = =0) {return "0"; }intMaxscale = Getmaxscale (Exacta, EXACTB); Changesacle (Exacta, Maxscale); Changesacle (EXACTB, Maxscale);LongSubnum = Exacta.getdata () * Exactb.getdata (); String resultinit = Getdatafromlong (Subnum, Maxscale *2);returnGetresultwithzero (Resultinit); }/** * For division, I didn't think of a good way to calculate exactly. And the division itself has a lot of not divisible, so the division is generally to determine a precision, and then calculate. The level is limited, here is an implementation of bigdecimal instead of it? */ Public StaticStringDivide(String stra, String StrB) {return NewBigDecimal (Stra). Divide (NewBigDecimal (StrB), Bigdecimal.round_down). toplainstring (); }Private Static void changesacle(Exactlong Exactdata,intMaxscale) {if(Maxscale! = Exactdata.getscale ()) {Exactdata.setdata (Long) (Exactdata.getdata () * MATH.POW (Ten, Maxscale-exactdata.getscale ()))); Exactdata.setscale (Maxscale); } }Private Static int Getmaxscale(Exactlong exacta, Exactlong EXACTB) {intMaxscale = Exacta.getscale () > Exactb.getscale ()? Exacta.getscale (): Exactb.getscale ();returnMaxscale; }/** * Shift the Datal decimal point to the left scale position * / Private StaticStringGetdatafromlong(LongDatal,intScale) {String datastr = datal +"";if(Scale <0) {Throw NewIllegalArgumentException ("the degree must greater than 0!!"); }if(Scale = =0) {returnDATASTR; }if(Datastr.length () > scale) {returnDatastr.substring (0, Datastr.length ()-scale) +"."+ datastr.substring (datastr.length ()-scale); }Else{StringBuilder DATASB =NewStringBuilder ("0."); for(inti =0; i < scale-datastr.length (); i++) {Datasb.append ("0"); } datasb.append (DATASTR);returnDatasb.tostring (); } }/** * Remove the extra 0 after the decimal point * / Private StaticStringGetresultwithzero(String resultinit) {intindex = Resultinit.length ();//Where the number of decimal places last possible multiple 0 for(inti = Resultinit.length ()-1; I >=0; i--) {if(Resultinit.charat (i)! =' 0 ') {index = i +1; Break; } }returnResultinit.substring (0, index); } Public Static void Main(string[] args) {String Stra ="0.001234560"; String StrB ="10.2345"; String stradd = Add (Stra, StrB); System.out.println ("add:\n"+ Stra +"\ n"+ StrB +"\ n"+ stradd); String strsub = Subtract (stra, StrB); System.out.println ("sub:\n"+ Stra +"\ n"+ StrB +"\ n"+ strsub); String Strmult = Multiply (stra, StrB); System.out.println ("mult:\n"+ Stra +"\ n"+ StrB +"\ n"+ Strmult); String Sttdiv = Divide (Stra, StrB); System.out.println ("div:\n"+ Stra +"\ n"+ StrB +"\ n"+ Sttdiv); }}/** * The floating-point number represented by a string is represented by a long, and the scale represents the right shift of the decimal point. */Class Exactlong {Private LongDataPrivate intScale Public Exactlong(String datastr) {if(Datastr.indexof (".") == -1) {//As 123456data = Long.parselong (DATASTR); Scale =0;return; }if(Datastr.indexof (".")! = Datastr.lastindexof (".")) {//As 123.456.7 Throw NewIllegalArgumentException (Datastr +"Can not cast to long!"); }Else{//As 12345.678Scale = Datastr.length ()-Datastr.indexof (".") -1;LongBeforepoint = Long.parselong (datastr.substring (0, Datastr.indexof (".")));//number before the decimal point LongAfterpoint = Long.parselong (datastr.substring (Datastr.indexof (".") +1, Datastr.length ()));//number after the decimal pointdata = (Long) (Beforepoint * MATH.POW (Ten, scale) + afterpoint); } } Public Long GetData() {returnData } Public void SetData(LongData) { This. data = data; } Public int Getscale() {returnScale } Public void Setscale(intScale) { This. scale = scale; }}
Using the long type in Java for precise arithmetic