This EE article provides JavaScript examples of conversion from string to integer, string to floating-point, and number to string. We'll also look at some related topics, including how to format numeric output with two decimal places, and one way to do right-justification of numeric text.
这篇EE文章提供了从字符串到整数,从字符串到浮点以及从数字到字符串JavaScript转换示例。 我们还将研究一些相关主题,包括如何用两位小数位格式化数字输出的格式,以及一种对数字文本进行右对齐的方法。
0.首先...简短答案 (0. First... The Short Answer)
//------------------ convert number to string
var n= 123; // n is a number -- value is one hundred-twenty-three
var s= ''+n; // s is a string with three characters -- value is '123'
//------------------ convert string to number
var s= '12 days'; // s is a string
var n= parseInt( s ); // n is a number -- value is twelve
parseInt() function is the most reliable way to break out a numeric value that's at the start of a string (or is the entire string).
parseInt()函数是最可靠的方法,可以分解字符串开头(或整个字符串)开头的数值。
0.自动转换 (0. Automatic Conversion)
JavaScript会自动为您完成大多数转换:var n=1234;
alert(n);
alert( 'The value is: ' + n );
alert function (or WScript.Echo) displays textual (string) data, so the parameter is converted automatically for you. The second example uses the fact that concatenating a number to a string forces an automatic conversion.
警报功能(或WScript.Echo )显示文本(字符串)数据,因此将自动为您转换参数。 第二个示例使用以下事实:将数字连接到字符串会强制自动转换。
However, there are cases where the built-in conversion might not work as hoped. For instance,
但是,在某些情况下内置转换可能无法按预期工作。 例如,
var nHundreds=1;
var nTens=2;
var nOnes=3;
alert( 'The answer is ' + nHundreds+nTens+nOnes ); // The answer is 123
alert( 'The answer is ' + (nHundreds+nTens+nOnes) ); // The answer is 6
alert( nHundreds+nTens+nOnes + ' is the answer' ); // 6 is the answer
var s= '7';
alert( nHundreds+nTens+nOnes +s+ ' is the answer' ); // 67 is the answer
+ operator will try to make the "sum" (the concatenation result of two operands) to be the same data type as the addend (the first operand).
+运算符将尝试使“ sum”(两个操作数的合并结果)与加数(第一个操作数)具有相同的数据类型。
In the second example (line5), the parentheses make the numeric calculation into a single number value, rather than three string values.
在第二个示例(第5行)中,括号使数值计算成为单个数字值,而不是三个字符串值。
The third example has three numeric values at the start, so it treats them as numbers when added. Then it encounters a string, so it converts the addend (a number) into a string for string concatenation.
第三个示例在开头有三个数字值,因此添加时将它们视为数字。 然后,它遇到一个字符串,因此将加数(一个数字)转换为字符串以进行字符串连接。
The fourth example is a bit more subtle. The fourth item (variable s) is a one-character string. One might think that JavaScript would convert it to a number so that it could be added to the previous numbers. But a string datatype always trumps a numeric datatype, so adding s is a string concatenation -- not a numeric addition.
第四个例子有些微妙。 第四项(变量
0.显式转换 (0. Explicit Conversion)
JavaScript提供了可用于避免任何歧义的运算符。 也就是说,您可以强制数据类型,而不是让语言解释器进行自动转换。The toString() function outputs a string. The parseInt() function outputs an integer number. For instance:
toString()函数输出一个字符串。 parseInt()函数输出一个整数。 例如:
var n1= 1; // a number
var n2= 2; // a number
alert( n1+n2 ); // shows 3 (a number)
alert( n1+n2.toString() ); // shows '12' (a string)
var s1= '1'; // a string
var s2= '2'; // a string
alert( s1+s2 ); // shows '12' (a string)
alert( parseInt(s1)+parseInt(s2) ); // shows 3 (a number)
0xnnnn as a hexadecimal input value. You can also explicitly select the numeric base using an optional second parameter (the radix). Examples:
0x
var s1='0xFF';
alert( parseInt(s1) ); // shows 255
var s2='ffff';
alert( parseInt(s2,16) ); // shows 65535
var s2='00000101';
alert( parseInt(s2,2) ); // shows 5 (decimal value of binary 101 )
Important notes about parseInt():
有关parseInt()的重要说明:
The parseInt() function discards any leading whitespace, then reads the string from left to right, stopping when it hits an unexpected character. That can be very useful. For instance, it lets you collect a numeric value at the start of a string without needing to know how many characters long it is:
parseInt()函数将丢弃所有前导空格,然后从左到右读取字符串,并在遇到意外字符时停止。 那可能非常有用。 例如,它使您可以在字符串的开头收集一个数值,而无需知道它有多少个字符:
var s= ' 100%</div>'; // a snip of HTML
alert( parseInt(s) ); // shows 100
var s1= '1,000,000.00';
alert( parseInt(s1) ); // shows 1
var s2= '123.99';
alert( parseInt(s2) ); // shows 123
var s3= '$123.99';
alert( parseInt(s3) ); // shows NAN (or 1.#QNAN)
isNaN() function:
isNaN()函数:
var n= parseInt( s );
if ( isNaN(n) ) {
... s was invalid input, do something. Don't display it.
}
if the text being parsed begins with a leading zero, it will be parsed as an octal number. That's fine for values like 007, but it can lead to confusing results...
如果要解析的文本以前导零开头,它将被解析为八进制数 。 像007这样的值很好,但是可能导致结果混乱。
alert( parseInt('011') ); // shows 9
alert( parseInt('011',10) ); // shows 11
0.字符串到浮点 (0. String to Floating-Point)
Up until now, we've assumed that you are converting to an integer. When your expected input value may contain a decimal point, you should use parseFloat(). For instance:
到目前为止,我们假设您正在转换为整数。 当期望的输入值可能包含小数点时,应使用parseFloat() 。 例如:
var s1= ' 12345.67 (low down payment)';
alert( parseFloat(s1) ); // shows 12345.67
var s2= ' 12345.00';
alert( parseFloat(s2) ); // shows 12345
toFixed(). Just specify 2 decimal places, and your output will show dollars and cents as expected:
toFixed() 。 只需指定2个小数位,您的输出将按预期显示美元和美分:
var s1= ' 12345.00';
var n1= parseFloat(s1); // value is 12345
alert( n1.toFixed(2) ); // shows 12345.00
var n2= 12345.666;
alert( n2.toFixed(2) ); // shows 12345.67 <<= Note: rounded up
Format as U.S. Currency
格式为美国货币
As the final tip for this article, here is a little routine that I use when I need a fixed-width output of a dollars and cents value. Pass in a number, and it outputs a string formatted as U.S. currency, with leading dollar sign, decimal point and two digits, commas separating thousands, millions, and billions, and it's padded with leading spaces so that columns of these formatted values will line up:
作为本文的最后一个技巧,这里是我需要美元和美分值的固定宽度输出时使用的一些例程。 传递一个数字,然后输出一个格式为美元的字符串,带有前导美元符号,小数点和两位数字,逗号分隔成千上万,数百万和十亿,并用前导空格填充,以使这些格式值的列都行向上:
//---- outputs a string value: (spaces)$n,nnn.nn
function toDollars( nValue, nWide ) {
var s= nValue.toFixed(2);
for( j=6; j<15; j+=4 ) { // insert commas
if ( s.length > j ) {
s= s.substr(0,s.length-j)+','+ s.substr(s.length-j);
}
}
s= '$'+s; // leading dollar sign
if ( !isNaN(nWide) ) { // parameter is present
while( nWide > s.length ) { // pad with leading spaces
s=' '+s;
}
}
return(s);
}
//usage example
var s= toDollars(1234567.88,15) +"\n";
s += toDollars( 17.88,15) +"\n";
s += toDollars( 0.888,15);
// output is:
// $1,234,567.88
// $17.88
// $0.89
References:参考文献:
JavaScript parseInt() Function
JavaScript parseInt()函数
http://www.w3schools.com/jsref/jsref_parseInt.asp http://www.w3schools.com/jsref/jsref_parseInt.aspJavaScript parseFloat() Function
JavaScript parseFloat()函数
http://www.w3schools.com/jsref/jsref_parseFloat.asp http://www.w3schools.com/jsref/jsref_parseFloat.aspJavaScript toString() Method
JavaScript toString()方法
http://www.w3schools.com/jsref/jsref_tostring_number.asp http://www.w3schools.com/jsref/jsref_tostring_number.aspJavaScript toFixed() Method
JavaScript toFixed()方法
http://www.w3schools.com/jsref/jsref_tofixed.asp http://www.w3schools.com/jsref/jsref_tofixed.asp =-=-=-=-=-=-=-=-=-=-=-=-=-
=-=-=-=-=-=-=-=-=-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=
If you liked this article and want to see more from this author, please click the Yes button near the:
如果您喜欢这篇文章,并希望从该作者那里获得更多信息,请单击旁边的是按钮:
Was this article helpful?
本文是否有帮助?
label that is just below and to the right of this text. Thanks!
此文字下方和右侧的标签。
=-=-=-=-=-=-=-=-=-=-=-=-=-
=-=-=-=-=-=-=-=-=-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=