Mark Wilson I am the creator of TopXML. I am available for international and local (Australia) contracts. I am a Solution Architect/Business Analyst. I have worked in IT in several countries (NZ, Australia, South Africa, UK) building and training teams for government and very large non-governmental organizations. I am ex-Microsoft Consulting Services. I wrote the first book on Microsoft XML published in 2000 called XML Programming with VB and ASP. Most recently I have been building tools for the SEO industry. Ask me for a 37 point SEO health-checkup for your website.
First posted :
03/24/2008
Times viewed :
2678
JavaScript Number <=> String Conversion
Introduction
JavaScript supports two types of conversions - Implicit or
Explicit. Implicit means that the conversion is done in run time from
JavaScript without any required step from you. Explicit means that you convert
the data type with a conversion function or something similar. Several
functions are available which will help for the conversion.
Implicit Conversion
<html>
<head>
<script type="text/javascript">
var nX = 2
// Implicit
conversion
document.write(nX)
</script>
</head>
<body></body>
</html>
Output
Explicit Conversion
<html>
<head>
<script type="text/javascript">
// ParseInt
var strX = "2"
var nX = parseInt(strX)
document.write("parseInt:
"+ nX + "<br/>")
// ParseFloat
strX = "2.7"
nX = parseFloat(strX)
document.write("parseFloat:
"+ nX + "<br/>")
// toString
strX = "2"
nX =
strX.toString()
document.write("toString:
" + nX + "<br/>")
// toFixed
nX = 3.149087
nX =
nX.toFixed(2)
document.write("toFixed:
" + nX + "<br/>")
//
toPrecision
nX = 3.149087
nX =
nX.toPrecision(2)
document.write("toPrecision:
" + nX + "<br/>")
//
toExponential
nX = 3.149087
nX =
nX.toExponential(2)
document.write("toExponential:
" + nX + "<br/>")
//
toLocaleString
nX = 3.149087
nX =
nX.toLocaleString(2)
document.write("toLocaleString:
" + nX + "<br/>")
// +
strX =
"99" + 1
document.write("+:
" + strX + "<br/>")
// -
strX =
"100" - 1
document.write("-:
" + strX + "<br/>")
</script>
</head>
<body></body>
</html>
Output
+ And –
When you use the + and – operators JavaScript does not
convert numeric values to strings. The following example demonstrates it.
Example
// +
strX = "99" + 1 //
Returns 991
// -
strX = "100" – 1 //
Returns 99
Functions
Name:
Description:
parseInt
Converts the string into an integer.
parseFloat
Converts the string into a float.
toString
Converts the number into a string.
toFixed
Returns the numbers of digits after the comma.
toPrecision
Returns the number of the total digits.
toExponential
Returns the number in exponential notation.
toLocaleString
Converts the number into the locale string format.