JavaScript is an accurate problem for floating point count operations

zhaozj2021-02-16  135

When using JavaScript to do floating point number operation, there will be error (no removal) when the number changes.

Such as 0.01 0.01 0.01 0.01 0.01 may be equal to 0.04999999 may be 0.05000000000000, which will have such a situation in the C language floating point operation.

In financial software, such a calculation is not allowed, there is a class that can be accurate in Java, but there is no similar class in JavaScript, only the method of accurate to the X bit has the following functions.

// Decoe's four rounds // f is your requirements for accurate floating point, size is accurate to the number of digits

Function Formatfloat (f, size)

{

VAR TF = f * Math.Pow (10, size);

Tf = Math.Round (TF 0.000000001);

Tf = TF / MATH.POW (10, size); Return TF;

}

//

Tf = Math.Round (TF 0.000000001);

It is the TF four, TF to add 0.000000001 because, according to JavaScript help, Round is rounded, but after I test, 0.5, it doesn't carry, add a little better (don't know why); actual effect: when I When set to 4 digits, the number of 0.0499999 will become 0.05 (reach the requirements, there is no problem now)

转载请注明原文地址:https://www.9cbs.com/read-8541.html

New Post(0)