Int() and Val() in JavaScript
Coders working with VB family of languages have tough time when it comes to Web development with JavaScript. They have choice of VBScript but that could not be considered for the want of cross-browser compatibility. One of such developers is me, myself. First it was my search for Asc() and Chr() in JavaScript and now I take here Int() and Val() functions. Lets start with code if you want in VB way.
<script>
function Int(StringorNum)
{
return parseInt(StringorNum);
}
function Val(String)
{
return parseFloat(String);
}
</script>
So here we are with two JavaScript functions parseInt() and parseFloat()
parseInt() is powerful than VB’s Int() function and takes two parameters (one optional) instead of one.
Syntax
parseInt(<string or number>, [<radix>])
The first parameter can be a string or a number. If it’s a string then leading and trailing spaces are ignored and the number if occurs in the beginning of the string is returned, decimal getting ignored as INTEGER is supposed to be returned.
If the string starts with “0x” the number following it is assumed to be hexadecimal and is converted to decimal before returning, so parseInt(”0×10″) would return 16.
The second parameter “radix” can be used to specify the base numeral system to be used, so parseInt(”11″,2), parseInt(”11″,8), parseInt(”10″,10), parseInt(”10″,16) would return 3,9,11,17 considering the first parameter to be binary, octal, decimal and hexa-decimal resp. You can use your own base numeral system specifying radix as any number between 2 and 36.
parseFloat() is similar to VB’s Val() function and takes a string parameter and extracts number values from the beginning of the string and includes decimal numbers.
Syntax
parseFloat(<string >)