Skip to content

Instantly share code, notes, and snippets.

@curran
Last active January 31, 2017 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curran/70348c8af4c1959c1289a20ff0a63490 to your computer and use it in GitHub Desktop.
Save curran/70348c8af4c1959c1289a20ff0a63490 to your computer and use it in GitHub Desktop.
Indian Number System Format
license: mit
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment