"Front-end" numeric conversions in layman's JavaScript

Source: Internet
Author: User
Tags bitwise operators

Since JavaScript is a weak type of language, type conversions are happening all the while in our code, so understanding the type conversion in JavaScript is critical to understanding how we know how JavaScript works.

This paper mainly from the numerical transformation of this dimension to analyze in JS, the numerical conversion will follow what rules, what is the purpose?

Under what circumstances will we use the value conversion in JS?
    1. In the traditional JS, we often need to calculate the length units when we transform, shift and change the size of the elements.
    2. When we provide a general add function, we need to restrict the type of the incoming parameter, not the non-numeric format;
    3. For more scenarios, follow the questions and answers: in which scenarios does the number () function in JavaScript work?
What numeric conversions exist in JavaScript?

We all know that there is an explicit type conversion and an implicit type conversion in JS, where explicit type conversions include:

    • Number ()
    • parseint ()
    • Parsefloat ()
    • Unary Plus and minus operators

Implicit type in JS in the embodiment of more complex, here is a simple list of the following situations:

    • Bitwise operators use number () to convert variables when manipulating non-numeric values, and then perform calculations;
    • Multiply/divide/subtract operators;
    • Relational operator (<,>,<=,>=);
    • Equality operator when one of the variables is numeric, the other variable is converted to a numeric value for comparison.

Because of the weakly typed nature of JS, implicit type conversions are relatively relative, and if you understand how a piece of code is converted into a type, it can be considered an explicit conversion for you.

Because implicit type conversions in JavaScript are basically done by calling the number function, this article mainly discusses the differences between explicit type conversions. Before we go into the discussion, let's look at a sample code:

1 var a = ' +3.14159test '; 2 3         var num1 = number (a);     NaN4var num2 = parseint (A, ten);      35var num3 = parsefloat (a);             3.141596var num4 = +A//NaN7var num5 =-A NaN
Number function features

Number () can be used to convert any type.

The ECMA specification describes the rules for number conversions:

https://tc39.github.io/ecma262/#sec-number-objects

Conversion rules
    • If the argument is Boolean, if True, returns 1;false returns 0;
    • If the number type, return directly;
    • Null returns 0,undefined return nan;
    • If it is an object, the ValueOf method is called first, if the return value can be converted to a numeric value, otherwise the ToString method is called, and the return value is returned according to the converted content of the other type rule;
    • If it is a string
      • Returns the decimal format of the numeric type if it contains only numeric types, or a negative number if there is a-sign in front of it;
      • An empty string returns 0;
      • A hexadecimal string returns a decimal number, or a Nan if there is a number in front of it;
      • If not a number, return nan;
1 varNUM1 = Number (true);//12 varnum2 = Number (false);//03 varnum3 = number (12);// A4 varNUM4 = number ();//05 varNUM5 = Number (NULL);//06 varNUM6 = number (undefined);//NaN7 varNUM7 = number (' 012 ');// A8 varNUM8 = number ('-012 ');//-129 varNUM9 = number (' 0x12 ');// -Ten varNUM10 = number (' -0x12 ');//NaN One varNUM11 = number (' 12test ');//NaN A varNUM12 = Number (// A - { -ValueOf:function (){ the         return' 012 ' - }, -Tostring:function () { -         return' 012test ' + } - } +)
parseint function Features

Used only to convert string types, the spaces preceding the string are ignored first. If the string starts with a number or a minus sign followed by a number, the string is returned to a non-numeric cutoff.

The ECMA specification rules description for parseint conversions

https://tc39.github.io/ecma262/#sec-parseint-string-radix

Conversion rules
    • Returns Nan If the first argument is not a string or a numeric type;
    • The first parameter is well formed, the second parameter does not pass the value
      • Returns Nan if the non-whitespace character at the beginning of the argument is not a non-numeric and non-plus minus sign
      • If the argument begins with 0x, the string is parsed in hexadecimal and the decimal format of the string is returned;
      • If the parameters of the beginning of 0, then in the ES3 standard in accordance with the eight-way resolution, the ES5 standard in accordance with the decimal to parse, and eventually return the decimal format;
    • The second parameter is passed, first the parameter two is converted to number ()
      • If the parameter two can be converted to a non-0 number, then the parameter is converted according to the corresponding binary
      • If parameter two cannot be converted to a non-0 number, then the parameter is NULL for processing
1 varNUM1 = parseint (' 0xf ');//15 with parseint (' +0xf ')2 varnum2 = parseint (' -0xf ');//-153 varnum3 = parseint (' 12test ');// A4 varNUM4 = parseint (' f ');//NaN5 varNUM5 = parseint (' f ', 16);// the6 varNUM6 = parseint (' 015 ', 8);// -7 varNUM7 = parseint (' 15.34 ');// the8 varNUM8 = parseint (' f ', ' 0x10 ');// the
parsefloat function Features

Similar to parseint, but only one parameter can be received, the incoming string is parsed only by 10, and the passed-in string is parsed into a double-type number.

The ECMA specification rules description for parseint conversions

https://tc39.github.io/ecma262/#sec-parsefloat-string

Conversion rules
    • Returns Nan If the first argument is not a string or a numeric type or a dot character;
1 var num1 = parsefloat ('  15.34.43 ');        // 15.34 2 var num2 = parsefloat (' 0x123.45 ');         // 0 because hexadecimal is not supported 3 var num3 = parsefloat ('  012.0test ');       // 12
Unary Plus and minus operators

The function of the unary plus operator is exactly the same as the number () function, and the unary minus operator takes a negative value on the basis of the plus operator.

Summary

When we can determine that the variable type being converted is a string type, it is preferable to use parsefloat, which can be used when the converted variable is decimal, and when using parseint, it is recommended to use the second parameter to determine the input type of parameter one, avoiding the compatibility problem of different browsers;

In the process of writing, the more we find the knowledge points involved, perhaps there are many places where there are flaws and errors. If you have any questions, please correct me!!!

"Front-end" numeric conversions in layman's JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.