The forced type conversion rules are: 1. Convert characters to numerical values. [parseInt()] converts from left to right once. If it can be converted, it will be converted. If it cannot be converted, it will stop. [Math.round()] is strictly converted and cannot be converted. Any non-numeric characters are allowed; 2. Convert numerical values to characters, [toString()] directly converts.
The forced type conversion rule is:
Character to value
parseInt();
Convert from left to right once. If it can be turned, it will be turned, and if it cannot be turned, it will stop; if it is the first place, it cannot be turned, and it will be NaN directly; the decimal point will not be recognized.
parseFloat();
Equivalent to parseInt, and can recognize decimal points
Math.round();
Strict conversion, no non-standard conversion is allowed Numeric characters, otherwise NaN; take the nearest integer
Number();
Strict conversion, no non-numeric characters are allowed, otherwise NaN; direct conversion
var str = "123";
var str = "123abc";
var str = "123abc456";
var str = "a123";
var str = "adasd";
var str = "123.45";
var n = parseInt(str);
console.log(str);
console.log(typeof str);
console.log(n);
console.log(typeof n);
var str = "a567.892";
var n = parseFloat(str);
console.log(str);
console.log(typeof str);
console.log(n);
console.log(typeof n);
var str = "-456.789";
var n = Math.round (str);
console.log(str);
console.log(typeof str);
console.log(n);
console.log(typeof n);
var str = "-456.789a";
var n = Number(str);
console.log(str);
console.log(typeof str);
console.log(n);
console.log(typeof n);
Numeric value to character
toString();
Direct conversion is equivalent to adding quotation marks to the value to be converted
Keep n as a decimal
toFixed();
While adding quotation marks, round to n decimal places. If it is not enough, add zeros
var n = 10.3543;
var s = n.toString( );
console.log(n);
console.log(typeof n);
console.log(s);
console. log(typeof s);
var n = 10;
var s = n.toFixed(2);
console.log(n);
console.log(typeof n);
console.log(s);
console.log(typeof s);
console.log(123.567000000)
Numeric value to character
var n = 123;
var s = n "";
console.log(s)
Character to value
var s = "123";
var n = s - 0;
console.log (n)
Other rotation values
true is 1, false is 0
console.log(1 true); //2
console.log(1 false); //1
console.log(1 undefined); //NaN
console.log(1 NaN); //NaN
console.log(1 null); //1
Related learning recommendations: Programming video
The above is the detailed content of What are the cast rules?. For more information, please follow other related articles on the PHP Chinese website!