View Full Version : String to decimal...
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
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
Thanks all, I don't know where I went wrong...
Glad to help you ???. (lol... what a name)
Rather than something convoluted like subtracting zero, to coerce to number all one need do is apply unary plus:
var n = +"7.012";
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.