Apparent age mangler

03/04/17

Permalink 10:01:27 am, by Greg, 176 words, 33 views   English (CA)
Categories: Activity log; Mins. worked: 5

Apparent age mangler

Attestation paper has a field that asks for apparent age in years and months. Using the example '30 years 4 months' as an example, we'll ask editors to enter it thusly 30:4

Here's some javascript that will take 30:4 and turn it in to 364. We'll store that in the database as an integer.

// incoming
var ageFromInput = "30:4";  // this needs to be a string
var ageArr = ageFromInput.split(':');
var ageSubYears = parseInt(ageArr[0]); // this needs to be an integer
var ageSubMonths = parseInt(ageArr[1]); // this needs to be an integer
var ageInMonthsYears = ageSubYears*12;
var ageInMonthsTotal = ageInMonthsYears+ageSubMonths; // should be 364
console.log(ageInMonthsTotal);

When we display the data, we'll reverse things, taking the 364 from the DB and turning it in to the correct display format

// outgoing
var ageInMonths = 364; // int value from DB
var ageDecimal = ageInMonths/12; // should give us 30.333333333333332
var ageYears = Math.floor(ageDecimal); // should give us 30
// to handle the months display, we need to get the decimal 
// value (0.333333333333332) with modulus (%), multiply by 12 and round
var ageMonthsRemainder = Math.round((ageDecimal % 1)*12); //should give us 4
var ageDisplay = ageYears + ":" + ageDecimalRemainder; // should give us 30:4
console.log(ageDisplay);

Pingbacks:

No Pingbacks for this post yet...

CGWP

Reports

XML Feeds