The Number module of the DataType Utility allows you to take a data value and convert it to a number.
To convert a data value to a number, simply call the parse() function of the Y.Number class:
YUI().use("datatype-number", function(Y) {
var output = Y.Number.parse("123123.123");
// output is the number 123123.123
});
Under the hood, the data value is converted to a number via +data, not parseInt(). When the resulting value is NaN, then null is returned:
YUI().use("datatype-number", function(Y) {
var output = Y.Number.parse("$100");
// output is null
output = Y.Number.parse("20 dollars");
// output is null
output = Y.Number.parse("3,000,000.12");
// output is null (it's the commas)
output = Y.Number.parse(new Date("Jan 1, 2000"));
// output is 946713600000
});
A configuration argument can be added to deal with these numbers.
YUI().use("datatype-number", function(Y) {
var output = Y.Number.parse("$100", {
prefix:'$'
});
// output is 100
output = Y.Number.parse("20 dollars", {
suffix: 'dollars'
});
// output is 20
output = Y.Number.parse("3,000,000.12" ,{
thousandsSeparator: ','
});
// output is 3000000.12
output = Y.Number.parse(new Date("Jan 1, 2000"));
// output is 946713600000
});
The following example uses the following configuration:
{
decimalSeparator: ',',
thousandsSeparator: '.',
prefix: '€',
suffix: '(EUR)'
}