0

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;
        }
}
user1149499
  • 573
  • 4
  • 12
  • 30
  • Why should 4.500 be displayed as 4500 and not 4.50? – showdev Oct 16 '13 at 19:23
  • @showdev Several countries use `.` instead of `,` as the [thousands separator](http://docs.oracle.com/cd/E19455-01/806-0169/overview-9/index.html). – Andrew Clark Oct 16 '13 at 19:32
  • Because in some countries in Europe the comma and decimal are swapped. So "4.500" = "4500" not "4.50" as it would in the USA. So as is the function works great, but it confuses "4.5" and "4,5" for "45" rather than "4.50" – user1149499 Oct 16 '13 at 19:32
  • Would it help if you knew the current locale decimal separator? http://stackoverflow.com/questions/1074660/with-a-browser-how-do-i-know-which-decimal-separator-does-the-client-use – Andrew Morton Oct 16 '13 at 19:34
  • Lots of relevant information here: http://stackoverflow.com/questions/5314237/javascript-convert-to-european-locale – Christian Ternus Oct 16 '13 at 19:35
  • @F.J Yes, but how will you tell the difference? I guess that's why the OP is checking for numbers that only have a tenths place. But it seems that 4.500 could be valid notation for 4.5, depending on your locale. – showdev Oct 16 '13 at 19:35
  • Currently there is no way to tell the difference and it's probably easier to just test for places than determine the relevant currency. @Christian, I checked that (before posting) but that assumes Euros for all data, whereas this could be dollars, or Euros, or even other currencies. That issue is not really important since the currency stays constant throughout, but I think it's unlikely that someone would write "4.5" or "4,5" and mean "45" so I'd like to turn that kind of entry into something more appropriate. Again, thank you for the help. :-) – user1149499 Oct 16 '13 at 19:40
  • @showdev, no, if someone wrote 4.500 it would be incorrect to have it become 4.50. – user1149499 Oct 16 '13 at 19:43
  • If I entered `4.500` and it came out as `4,500`, I'd be confused. It seems like you should be checking the current locale, as mentioned by @AndrewMorton. But I realize that this is a tangent to your actual question and is probably better discussed elsewhere. – showdev Oct 16 '13 at 19:49
  • @showdev, yes, exactly -- for other reasons I've opted to do it this way rather than via locale. Ideally I'd just like to know how to modify the code to turn "?.?" and "?,?" into "?.?0" and "?,?0" Anyone know the simplest way to accomplish this? – user1149499 Oct 16 '13 at 19:52
  • What I have above works perfectly EXCEPT that it doesn't do the X.X and X,X cases correctly. Maybe that wasn't clear? I just need to turn X,X into X,X0 and X.X into X.X0 and all will be fine. – user1149499 Oct 16 '13 at 20:43

2 Answers2

0

If I understand you correctly this should do it

function parse(s) {
    var found = false;
    ['.', ','].forEach(function (el) { 
        var i = s.indexOf(el);
        if (s[i] === s[s.length - 2]) {
            s = s + '0';
            found = true;
            return false;
        }
    });
    if (!found) {
        return s.replace(/(\.|,|\s)/g, '');
    } else {
        return s;
    }
}

Run a forEach on each delimiter and figure out how you want it to be formatted.

http://jsfiddle.net/Ek6cJ/

beautifulcoder
  • 10,832
  • 3
  • 19
  • 29
  • This isn't quite working, I added an alert on each of the returns and it's going through once for the latter but twice for the former...it should only check once...if the pattern matches "X,X" or "X.X" then change to "X,X0" or "X.X0"...and return... – user1149499 Oct 16 '13 at 20:28
0

Does this do what you want?

function parse(source) {
    var dotIndex = source.lastIndexOf('.');
    var commaIndex = source.lastIndexOf(',');
    var numDots = source.match(/\./g).length;
    if (dotIndex > commaIndex && numDots == 1) {
        // Dot-delimited decimal
        return Number(source.replace(/,/g, '')).toFixed(2);
    } else {
        return Number(source.replace(/\./g, '').replace(/,/g, '.')).toFixed(2);
    }
}

> parse("1,200,300.20")
"1200300.20"
> parse("1.200.300,20")
"1200300.20"
> parse("1.200.300")
"1200300.00"
Christian Ternus
  • 8,406
  • 24
  • 39
  • No, this looks to do exactly what I've already got working. (Albeit different code.) What I want is a simple function that turns the pattern XBx into XBx0 where X="digits" B= "comma or period" and "x" = "0-9 (just one digit)" Maybe I'm just explaining this unclearly? – user1149499 Oct 16 '13 at 20:01