0

I have created a function that takes a number in Imperial units entered into a div and converts that value to metric units in another div. Being relatively new to js, I am now realizing that a thousandths place comma separator does not come standard. I've tried to apply many of the solutions (many of them reg ex's) that I've found but none suit my needs or have worked. Simply put, I am just looking to have both divs outputted numbers have commas separating the thousandths place. Ultimately, these numbers are elevation values expressed in Feet and Meters. Any insight would be greatly appreciated... thanks!

Here is my code:

<body>

<div id="feet" onload="calculateMeter()">2120</div>
<div id="meter"></div>

<script>
var feet = document.getElementById('feet');
var meter = document.getElementById('meter');

function calculateMeter() {
    if (feet.innerHTML > 0) {
        meter.innerHTML = (feet.innerHTML  *  0.3048).toFixed(1);
        feet.toString();
        feet = feet.innerHTML.replace(/(\d)(\d{3})\,/, "$1,$2.");
    } 
}
calculateMeter();


</script>                           
</body>
  • 1
    There is [a new DOM API called Intl](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat) for formatting numbers and other things according to the user locale, it may help you – aarosil Apr 28 '16 at 15:58
  • Like I said, I've researched many solutions, this one included, to no avail. Please help. – Michael Sabatini Apr 28 '16 at 16:06
  • The problems seems to be that you don't know how to update the content of the HTML? What's the purpose of `feet.toString();`? Why are you assigning to `feet`? Do you want `feet.innerHTML = feet.innerHTML.replace(...)` instead? – Felix Kling Apr 28 '16 at 16:15
  • From what I read, I need to convert the integer into a string and then add the comma from there. Again, I am novice in js which is why I defer to the experts on SO for help. So, forget the feet.toString part and focus on the if statement and function above it. My bad for not deleting that part. – Michael Sabatini Apr 28 '16 at 16:20
  • Well, `feet` is a DOM element, not an integer, so I don't understand what you are trying to achieve with `feet.toString()`. It really seems all you want is `feet.innerHTML = feet.innerHTML.replace(/\B(?=(\d{3})+(?!\d))/g, ",");` – Felix Kling Apr 28 '16 at 16:34

3 Answers3

0

My function:

function formatNumberWithCommasDec(d) {
      d += "";
      var c = d.split(".");
      var f = c[1];
      var a = c.length > 1 ? c[0] + '.' : '.', flag = false;
      var g = f.split('').reverse(), y = 1, s = '';
      for (var i = g.length - 1; i >= 0; i--) {
        flag = false;
            var e = g[i];
        var h = (y === 3) ? s = s + e + ',' : s = s + e;
        console.log(e);
        if(y === 3){
            y = 1;
          flag = true;
        } else {
            y = y + 1;
        }
            }
     if(flag){
            s = s.substring(0, s.length - 1);
     } else {
            s = s;
     }
     return a + s;     
  }

Fiddle: https://jsfiddle.net/6f0tL0ec/1/

Update: found some problems, but everythings good now

Derek Pollard
  • 6,953
  • 6
  • 39
  • 59
0

It seems your problem is actually just setting the content the DOM element. Using the solution in How to print a number with commas as thousands separators in JavaScript for formatting numbers, all you need is:

function calculateMeter() {
    if (feet.innerHTML > 0) {
        meter.innerHTML = numberWithCommas*(feet.innerHTML * 0.3048).toFixed(1));
        feet.innerHTML = numberWithCommas(feet.innerHTML);
    } 
}
Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    He said thousand**ths** place, not thousands – Derek Pollard Apr 28 '16 at 17:05
  • @OliverQueen: Interesting. Though that might just be incorrectly expressed by the OP. Is this a common way to format a number though? I have never seen something like this... – Felix Kling Apr 28 '16 at 17:08
  • I have no idea, but he says it multiple times, and there *are* tons of functions for a normal comma sep script online... – Derek Pollard Apr 28 '16 at 17:11
  • 1
    @OliverQueen: Right, but looking at the OP's code, I wouldn't expect them understand how to use them. I still believe this more of an issue of how to use such a function. Anyways, it's good to have different interpretations of the problem, that gives the OP more choice and will hopefully help them better :) – Felix Kling Apr 28 '16 at 17:12
0

Here is a simple RegEx solution

function calculateMeter() {
    if (feet.innerHTML > 0) {
        var m = (feet.innerHTML  *  0.3048).toFixed(2);
        meter.innerHTML = m.replace(/\B(?=(\d\d\d)+\b)/g, ",");
    }  
}
jjpcondor
  • 1,386
  • 1
  • 19
  • 30
  • 1
    Ok! This worked, thanks so much! I even took your code and worked in a few new lines that adds the comma to the "feet" div as well. Whenever I've had an issue in the past, I've always been able to find it online, but not this time. Glad I asked the question. Thanks again to everyone for all of their input. I really appreciate it! – Michael Sabatini Apr 28 '16 at 19:27