Common functions and code for JS variable type conversion [comprehensive]

Source: Internet
Author: User
Tags type casting

1. conversion functions:

JS provides two conversion functions: parseint () and parsefloat. The former converts the value to an integer, and the latter converts the value to a floating point number. The two functions can run correctly only when these methods are called for the string type. Nan (not a number) is returned for other types ).

Before determining whether a string is a numeric value, parseint () and parsefloat () will carefully analyze the string. The parseint () method first checks the character at the position 0 to determine whether it is a valid number. If not, the method returns Nan and does not continue to perform other operations. However, if the character is a valid number, this method will view the characters at position 1 and perform the same test. This process continues until a non-valid number is found. At this time, parseint () converts the string before this character into a number.

For example, if you want to convert the string "1234 blue" to an integer, parseint () returns 1234 because the detection process stops when it detects character B. The number literal in the string is correctly converted to a number, so the string "0xa" is correctly converted to a number 10. However, the string "22.5" is converted to 22 because the decimal point is invalid for integers. Some examples are as follows:

Parseint ("1234 blue"); // returns 1234
Parseint ("0xa"); // returns 10
Parseint ("22.5"); // returns 22
Parseint ("blue"); // returns Nan

The parseint () method also has the base mode, which can convert binary, octal, hexadecimal, or any other hexadecimal string to an integer. The base is specified by the second parameter of the parseint () method. to parse the hexadecimal value, you need to call the parseint () method as follows:
Parseint ("af", 16); // returns 175
Of course, for binary, octal, or even decimal (default mode), you can call the parseint () method as follows:
Parseint ("10", 2); // returns 2
Parseint ("10", 8); // returns 8
Parseint ("10", 10); // returns 10
If the decimal number contains the leading 0, it is best to use base 10 to avoid unexpected octal values. For example:
Parseint ("010"); // returns 8
Parseint ("010", 8); // returns 8
Parseint ("010", 10); // returns 10
In this sectionCodeBoth lines of code parse the string "010" into a number. The first line of code regards this string as the octal value. The method for parsing this string is the same as that of the second line of code (The Declaration base is 8. The last line of Code declares that the base number is 10, so inum3 is equal to 10 at last.

The parsefloat () method is similar to the parseint () method. Each character is viewed from position 0 until the first invalid character is found, then, convert the string before the character to a number. However, for this method, the first decimal point is a valid character. If there are two decimal points, the second decimal point is considered invalid. The parsefloat () method converts the string before the decimal point to a number. This means that the string "22.34.5" will be parsed to 22.34.
Another difference in using parsefloat () Is that a string must represent a floating point in decimal format, rather than octal or hexadecimal format. The
The method ignores the leading 0, so 0908 of the Octal numbers will be parsed to 908. For the hexadecimal number 0xa, this method returns Nan because X is not a valid character in the floating point number. In addition, parsefloat () does not have a base mode.

The following is an example of using parsefloat:
Parsefloat ("1234 blue"); // returns 1234.0
Parsefloat ("0xa"); // returns Nan
Parsefloat ("22.5"); // returns 22.5
Parsefloat ("22.34.5"); // returns 22.34
Parsefloat ("0908"); // returns 908
Parsefloat ("blue"); // returns Nan

2. Forced type conversion

You can also use type casting to process the type of the converted value. You can use forced type conversion to access a specific value, even if it is another type.
The three types of mandatory conversions available in ecmascript are as follows:
Boolean (value) -- converts a given value to the boolean type;
Number (value) -- converts a given value to a number (which can be an integer or floating point number );
String (value) -- converts a given value to a string.
Use one of the three functions to convert a value and store the value directly converted from the original value. This will cause unexpected consequences.
When the value to be converted is a string of at least one character, a non-zero number, or an object (This will be discussed in the next section), the Boolean () function returns true. If the value is a Null String, number 0, undefined, or null, it returns false.

You can use the following code snippet to test the forced type conversion of the boolean type.

Boolean (""); // false-empty string
Boolean ("hi"); // true-non-empty string
Boolean (100); // true-non-zero number
Boolean (null); // false-Null
Boolean (0); // false-zero
Boolean (new object (); // true-Object

The forced type conversion of number () is similar to that of parseint () and parsefloat (), except that it converts the entire value instead of the partial value. Do you still remember that the parseint () and parsefloat () methods only convert strings before the first invalid character, so "4.5.6" will be converted to "4.5 ". Use number () for forced type conversion. "4.5.6" will return Nan because the entire string value cannot be converted to a number. If the string value can be fully converted, number () determines whether to call the parseint () method or the parsefloat () method. The following table describes how to call the number () method for different values:

Result through Method
Number (false) 0
Number (true) 1
Number (undefined) Nan
Number (null) 0
Number ("5.5") 5.5
Number ("56") 56
Number ("5.6.7") Nan
Number (new object () Nan
No. (100) 100

The last forced type conversion method string () is the simplest, because it can convert any value into a string. To perform this forced type conversion, you only need to call the tostring () method of the value passed as the parameter, that is, convert 1 to "1" and convert true to "true ", convert false to "false", and so on. The only difference between forced conversion to a string and calling the tostring () method is that forced type conversion to a null or undefined value can generate a string without sending an error:

VaR S1 = string (null); // "null"
VaR onull = NULL;
VaR S2 = onull. tostring (); // won't work, causes an error

3. Weak type conversion using JS Variables

Let's take a small example. At first glance, we will understand.
<SCRIPT>
VaR STR = '012. 345 ';
VaR x = The str-0;
X = x * 1;
</SCRIPT>

In the above example, the weak type of JS is used for only arithmetic operations to convert strings to numbers. However, this method is not recommended.
// convert an object to a character
function object2string (OBJ) {
var val, output = "";
If (OBJ) {
output + = "{";
for (var I in OBJ) {
val = OBJ [I];
switch (typeof Val) {
case ("object"):
If (Val [0]) {
output + = I + ": "+ array2string (VAL) +", ";
}else {
output + = I +": "+ object2string (VAL) + ",";
}< br> break;
case ("string"):
output + = I + ": '" + Val + "',";
break;
default:
output + = I + ":" + Val + ",";
}< BR >}< br> output = output. substring (0, output. length-1) + "}";
}< br> return output;
}

Convert an array to a string
Function array2string (array ){
VaR output = "";
If (array ){
Output + = "[";
For (var I in array ){
Val = array [I];
Switch (typeof Val ){
Case ("object "):
If (Val [0]) {
Output + = array2string (VAL) + ",";
} Else {
Output + = object2string (VAL) + ",";
}
Break;
Case ("string "):
Output + = "'" + encodeuri (VAL) + "',";
Break;
Default:
Output + = Val + ",";
}
}
Output = output. substring (0, output. Length-1) + "]";
}
Return output;
}

Function string2object (string ){
Eval ("Var result =" + decodeuri (string ));
Return result;
}

Function string2array (string ){
Eval ("Var result =" + decodeuri (string ));
Return result;
}
Convert the date type to string format in JS

<Script language = "JavaScript">
/// // E ////// /////////////////
// Obtain the current date, in the format of yyyy-mm-dd
//////////////////////////////////////// ////////////////
Function getcurrentdate ()
{
VaR year = 0;
VaR month = 0;
VaR day = 0;
VaR currentdate = new date ();
Return changedatetostring (currentdate );
}

/// // E ////// /////////////////
// Obtain the current date in the format of yyyy-mm-dd hh: mm
//////////////////////////////////////// ////////////////
Function getcurrenttime ()
{
VaR year = 0;
VaR month = 0;
VaR day = 0;
VaR currentdate = new date ();
Return changetimetostring (currentdate );
}

//////////////////////////////////////// ////////////////
// Convert the date type to the string format yyyy-mm-dd
//////////////////////////////////////// ////////////////
Function changedatetostring (datein)
{
VaR year = 0;
VaR month = 0;
VaR day = 0;
VaR currentdate = "";
// Initialization time
Year = datein. getyear ();
Month = datein. getmonth () + 1;
Day = datein. getdate ();

Currentdate = year + "-";
If (month> = 10)
{
Currentdate = currentdate + month + "-";
}
Else
{
Currentdate = currentdate + "0" + month + "-";
}
If (day> = 10)
{
Currentdate = currentdate + Day;
}
Else
{
Currentdate = currentdate + "0" + Day;
}

return currentdate;
}< br> ///////////////////////////////// //// //
// convert the date type to the string format yyyy-mm-dd. hh: mm
//////////////////////////////////// ////// //
function changetimetostring (datein)
{< br> var year = 0;
var month = 0;
var day = 0;
var hour = 0;
var minute = 0;
var currentdate = "";
// initialization time
year = datein. getyear ();
month = datein. getmonth () + 1;
day = datein. getdate ();
hour = datein. gethours ();
minute = datein. getminutes ();

currentdate = year + "-";
If (month> = 10)
{< br> currentdate = currentdate + month + "-";
}< br> else
{< br> currentdate = currentdate + "0" + month + "-";
}< br> If (day> = 10)
{< br> currentdate = currentdate + Day;
}< br> else
{< br> currentdate = currentdate + "0" + day;
}< br> If (hour> = 10)
{< br> currentdate = currentdate + "" + hour;
}< br> else
{< br> currentdate = currentdate + "0" + hour;
}< br> If (minute> = 10)
{< br> currentdate = currentdate + ":" + minute;
}< br> else
{< br> currentdate = currentdate + ": 0 "+ minute;
}< br> return currentdate;
}< br>

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.