0

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/

2
  • This would be so much easier to help with if we could see your HTML. Could you post that? And, ideally, a JS Fiddle demo? Commented Dec 1, 2011 at 21:51
  • Here's the HTML with JS -> jsfiddle.net/hhWDe/5 Commented Dec 1, 2011 at 22:17

4 Answers 4

1

Force a data type on this:

var bctf = parseFloat(document.getElementById('buyctf').value);
Sign up to request clarification or add additional context in comments.

1 Comment

That's because the rest of your code is treating it as a string. It's a number now. i.e. bctf.charAt(0) == "0", expects a string. Adjust your code accordingly.
1

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"

Comments

1

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;

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.