yanike
yanike

Reputation: 847

Javascript Operators Issue working with Decimals

I got everything almost where I want it. My only problem is that for some reason I can't get the bctf1 to add right. Say if bctf = 10, the result with the code would be 100.59 instead of 10.59. Say if bctf = 25, the result with the code would be $251.03 instead of 26.03.

// BUY TOTAL
<script type="text/javascript">
function buytot(){
var bctf = document.getElementById('buyctf').value;
if(bctf.charAt(0) == "0" || bctf.charAt(0) == "" || bctf.charAt(0) == " "){
bctf2 = "0.00";
} else {
pcbctf = bctf*.029;
pcplusc = pcbctf+.30;
bctf1 = bctf+pcplusc;
bctf2 = Math.round(bctf1*100)/100;
}
document.getElementById('buyctotal').innerHTML = bctf2;
}
</script>

Here's the HTML with JS -> http://jsfiddle.net/hhWDe/5/

Upvotes: 0

Views: 334

Answers (4)

yanike
yanike

Reputation: 847

Thank You all :) This is the working code. I add bctf0 = Number(document.getElementById('buyctf').value); after the else and everything worked fine.

// BUY TOTAL
function buytot(){
var bctf = document.getElementById('buyctf').value;
if(bctf.charAt(0) == "0" || bctf.charAt(0) == "" || bctf.charAt(0) == " "){ bctf2 = "0.00";
} else {
bctf0 = Number(document.getElementById('buyctf').value);
pcbctf = bctf0*.029;
pcplusc = pcbctf+.30;
bctf1 = bctf0+pcplusc;
bctf2 = Math.round(bctf1*100)/100;
}
document.getElementById('buyctotal').innerHTML = bctf2;
}

Upvotes: 0

Jan
Jan

Reputation: 230

You can add "+" to convert a value to an integer (or float).

It will take any string and convert it, if the string cannot be converted, it will return NaN:

So your script would look like the following:

var bcft = +document.getElementByID('buyctf').value;

Upvotes: 1

maerics
maerics

Reputation: 156434

You need to convert the String values returned by the element value properties into numbers. Something like this:

var bctf = Number(document.getElementById('buyctf').value);
// OR
var bctf = parseFloat(document.getElementById('buyctf').value, 10);

Also, consider using the "toFixed" number method to get the ".00 decimal places for whole dollar amounts:

var oneDollar = 1;
oneDollar; // => 1
oneDollar.toFixed(2); // => "1.00"

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114377

Force a data type on this:

var bctf = parseFloat(document.getElementById('buyctf').value);

Upvotes: 1

Related Questions