Oct
19
2011

MooTools Integers and Floats when used in math and currency

We have all been there before, your creating a form and asking for a dollar amount, or some number with decimal points lets say amount of fuel purchased.

Typically there is plenty of logic that needs to go into validating the user input, did they use a dollar sign? Did they use the correct amount of decimal points?

Well MooTools and JavaScript to the rescue!

The MooTools

String.implement({
	cleanFloat: function() {
		return this.replace(/[^0-9.]/g,'').toFloat() || 0;
	}
});

String.implement({
	toCurrency: function() {
		return parseFloat(Math.round(this * 100) / 100).toFixed(2)
	}
});

Example Usage:

<input type="input" name="fuelCost" id="fuelCost" value="$4.28r9" />
<input type="input" name="gallons" id="gallons" value="75.9869 Gallons" />
<script>
window.addEvent('domready', function(){
	console.log(document.id('fuelCost').get('value').cleanFloat());
	// returns 4.289
	console.log(document.id('gallons').get('value').cleanFloat());
	// returns 75.9869

	// Now lets do some math
	console.log('$'+
		String.from(
			document.id('fuelCost').get('value').cleanFloat() *
			document.id('gallons').get('value').cleanFloat()
		).toCurrency()
	)
	// Return the total purchase price of $325.91
});
</script

*Tested with mooTools 1.3 and 1.4

Leave a comment

Show/Hide Footer Actions

Status: Available for your project.