block by curran 70348c8af4c1959c1289a20ff0a63490

Indian Number System Format

Full Screen

A first stab at an implementation of an Indian Number System format. Inspired by d3-format issue:Indian Number System format.

Updated June 17, 2016 to fix cases of “10000” and negative numbers, thanks to contributions by @Harshit20051.

Built with blockbuilder.org

web counter

index.html

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
  <style>
    
    .left {
      position: fixed;
      left: 5%;
    }
    
    .right {
      position: fixed;
      left: 55%;
    }
    
    p {
      font-size: 1.2em;
    }
  </style>
</head>

<body>
  <div class="left">
  </div>
  <div class="right">
  </div>
  <script>

    // Formats a number to a string using the Indian Number System Format.
    function format(x){
      var negative = x < 0,
          str = String(negative ? -x : x),
          arr = [],
          i = str.indexOf("."),
          j;

      if(i === -1){
        i = str.length;
      } else {
        for(j = str.length - 1; j > i; j--){
          arr.push(str[j]);
        }
        arr.push(".");
      }
      i--;

      for(j = 0; i >= 0; i--, j++){
        if(j > 2 && (j % 2 === 1)){
          arr.push(",");
        }
        arr.push(str[i]);
      }

      if(negative){
        arr.push("-");
      }

      return arr.reverse().join("");
    }
    
    var data = [
      10,
      100,
      1000,
      10000,
      100000,
      1000000,
      10000000,
      10000000.4543,
      1000.321,
      10.5
    ];
    
    d3.select(".left").selectAll("p").data(data)
      .enter().append("p")
      .text(function (d){
        return "format(" + d + ") = " + format(d);
      });
   
    var dataNegative = data.map(function (d){ return -d; });
    
    d3.select(".right").selectAll("p").data(dataNegative)
      .enter().append("p")
      .text(function (d){
        return "format(" + d + ") = " + format(d);
      });
    
  </script>
    
</body>