PDA

View Full Version : String to decimal...



???
01-04-2009, 04:38 AM
I should probably know this, but I don't without writing my own function. Here it is: How do I convert a string to a decimal. As in change "7.012" (a string) to 7.012 (a number). "parseFloat" doesn't appear to do it. It rounds it off to 7. And, "parseInt", I would assume is integers only.

Thanks,
Stephen

Nile
01-04-2009, 04:45 AM
Looks like your confusing parseInt with parseFloat... ParseInt will round, parseFloat will not round.
ParseFloat:


<script type="text/javascript">
window.onload = function(){
var typeE = "7.012";
alert("Before parseFloat(): "+typeof(typeE)+": "+typeE);
typeE = parseFloat(typeE);
alert("After parseFloat(): "+typeof(typeE)+": "+typeE);
}
</script>

This alerts:


Before parseFloat(): string: 7.012

After parseFloat(): number: 7.012


ParseInt:



<script type="text/javascript">
window.onload = function(){
var typeE = "7.012";
alert("Before parseInt(): "+typeof(typeE)+": "+typeE);
typeE = parseInt(typeE);
alert("After parseInt(): "+typeof(typeE)+": "+typeE);
}
</script>

This alerts:


Before parseInt(): string: 7.012

After parseInt(): number: 7

jscheuer1
01-04-2009, 12:47 PM
Unless your string also contains trailing non-numeric characters, or you want only its integer component, or change its base, you don't need to parse it at all. It is true though that parseInt will lop off the decimal places (not round the value, actually more like the Math.floor() method). The two parse methods are primarily for removing trailing non-numeric characters and/or converting between bases. In this case all we need do is subtract 0:


var n = "7.012" - 0;
alert(typeof n + ' ' + n);

alerts:


number 7.012

???
01-04-2009, 05:01 PM
Thanks all, I don't know where I went wrong...

Nile
01-04-2009, 06:22 PM
Glad to help you ???. (lol... what a name)

Twey
01-04-2009, 08:42 PM
Rather than something convoluted like subtracting zero, to coerce to number all one need do is apply unary plus:
var n = +"7.012";