I am wondering if this code can be modified so that it will render "4,5" and "4.5" (or any number that only has a tenths place) as 4.50 (or 4,50) respectively...rather than as 45.
I think I need to test "source" first to see if it's got the format "x[.,]x" (digit, comma or period, digit) but haven't been able to do that successfully. I've tried using "toFixed" but that messes things up if it's 4.500 or something (which needs to render as 4500, not 4.50!)
Any help would be hugely appreciated. Thank you!
function parse(source) {
var sep = source.charAt(source.length - 3);
switch (sep) {
case '.':
case ',':
var parts = source.split(sep);
var norm = parts[0].replace(/(\.|,|\s)/g, '') + '.' + parts[1];
break;
default:
var norm = source.replace(/(\.|,|\s)/g, '');
}
return Math.round(Number(norm));
}
So I have figured out a regex that identifies the right pattern: /^\d{1}[.,]\d{1}$/ (note there's a slash not showing up right before the period inside the brackets!!)
I have added it into the following little function, which I want to just tack on a zero or leave the variable as is. But for some reason it's now crashing at the part where I'm adding the zero...
function addZeros(number) {
var s = number;
if (s.match(/^\d{1}[\.,]\d{1}$/)) { //should only get here on "X,X" or "X.X" cases
alert(s); //makes it to here, displays only this alert
s = s.toFixed(2); //wtf is wrong with this?!!
alert(s); //does NOT make it to here.
return s;
}
else {
alert('All good in the hood.');
return s;
}
}