js and scientific notation

foreword

Let's look at a few examples

let a;
a = 0.0000001;
console.log(a); // 1e-7
a = 0.0000002;
console.log(a); // 2e-7
a = 0.00000008;
console.log(a); // 8e-8
a = -0.0000001;
console.log(a); // -1e-7

Scientific notation

Scientific notation is a method of counting numbers. Express a number in the form of multiplying a by the nth power of 10 (1≤a<10, n is an integer). Use scientific notation to save a lot of wasted space and time.

Based on the preface example, let's try again:

let a;
a = 0.0000001;
console.log(a); // 1e-7
'0.0000001'.split('.')[1].length; // 7
a = 0.0000002;
console.log(a); // 2e-7
'0.0000002'.split('.')[1].length; // 7

Summary rule: The so-called 1e-7 is actually 1 times 0.1 to the 7th power

2e-7 is actually 2 times 0.1 to the 7th power

Therefore: n * 0.1 (ie e) ∧ x

Scientific notation does not affect calculations

var a = 0.0000002;
var b = 0.0000001;
a + b; // 3e-7
var a =  0.0000001;
a + 2;  // 2.0000002

Solve the problem of scientific notation front-end display

Although scientific notation can save the calculation space of js, it cannot be directly used to display on the front-end page. So we should:

function getFullNum(num){
    //处理非数字
    if(isNaN(num)){return num};
    //处理不需要转换的数字
    var str = ''+num;
    if(!/e/i.test(str)){return num;};
    return (num).toFixed(18).replace(/\.?0+$/, "");
}
getFullNum(8.1e-7);// 0.00000081

Guess you like

Origin blog.csdn.net/weixin_42274805/article/details/129276571