PDA

View Full Version : negative values not showing

mhodgson
05-02-2007, 11:51 AM
Have a problem, hope someone can help,

If have worked on a script, where scoredage is a number like 8.5 (meaning years.months) and ageInMonths2 is a number like 60

<script type="text/javascript">

/** Function to calculate Scored Age variances**/

function variance(scoredage, ageInMonths2){

var yearfield = scoredage.split(".")[0]
var monthfield = scoredage.split(".")[1]
var yearfield = yearfield*12

var scoredmonths = parseInt(monthfield) + parseInt(yearfield)
var variance = scoredmonths - ageInMonths2
document.write(variance)

}

</script>

Seems to work fine as long as the final output 'variance' is positive. If the value ends up negative 'e.g. -21 or 0 then all I get displayed is NaN.
Can't figure out why?

The output is displayed in a repeat region of a php page and I found I had to put var on all the lines to get something to display on each row.

Twey
05-02-2007, 03:09 PM
var yearfield = scoredage.split(".")[0]
var monthfield = scoredage.split(".")[1]You're calling the split() function twice when it's only necessary once.
var yearfield = yearfield*12You've already defined yearfield.
var scoredmonths = parseInt(monthfield) + parseInt(yearfield)yearfield is already a number, but if either can't be parsed as an integer this will result in the result being NaN. You must also specify a base when using parseInt(), lest odd things happen (E.G. parseInt("011") is 9, because a leading 0 is interpreted as a sign of an octal number).
function variance(scoredAge, otherAgeMonths) {
return Math.abs(parseInt((scoredAge = scoredAge.toString().split("."))[0], 10) * 12 + parseInt(scoredAge[1], 10) - otherAgeMonths);
}

mhodgson
05-03-2007, 12:19 PM
Thanks for the help.
Your suggestion didn't quite work- probably my faulty code elsewhere.
However I modified mine using your ideas and came up with

function variance(scoredage, ageInMonths2){

scoredage = scoredage.split(".")
yearfield = parseInt(scoredage[0], 10)
monthfield = parseInt(scoredage[1], 10)

yearfield = yearfield*12

scoredmonths = monthfield + yearfield
var variance = scoredmonths - ageInMonths2

document.write (variance)

}

It now works fine.
Turns out the biggest problem ( all those NaN's) wasn't the javascript but the fact that the mysql table the data was being pulled from was missing data from several fields.

Thanks for the help I have actually learned quite a bit anout Javascript from solving this problem.

Twey
05-03-2007, 12:21 PM
function variance(scoredAge, otherAgeMonths) {
return Math.abs(parseInt((scoredAge = scoredAge.toString().split("."))[0], 10) * 12 + parseInt(scoredAge[1], 10) - otherAgeMonths);
}Note that this function returns the value, not writing it. If you wanted to write it, you could do:
document.write(variance(age1, age2));However, I don't recommend you use document.write().