Last active
August 29, 2015 14:07
-
-
Save ses4j/7b0705b3dd983797852b to your computer and use it in GitHub Desktop.
Format javascript number as an actually-readable string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Format javascript number as an actually-readable string | |
// using different d3.formats for different magnitudes. | |
// If it's NaN or otherwise not a number (ie a string), pass it through. | |
// For instance: | |
// 0.0000103 -> 10.3µ | |
// 0.000103 -> 0.000103 | |
// 0.103 -> 0.103 | |
// 10.34 -> 10.3 | |
// 1034 -> 1,034 | |
// 1034.1 -> 1,034.1 | |
// 10341.2 -> 10.3k | |
// 1034123 -> 1.03M | |
// 0.000 -> 0 | |
// "hi mom" -> "hi mom" | |
// undefined -> undefined | |
// null -> null | |
// See fiddle at http://jsfiddle.net/ses4j/bua30ko0/ | |
(function () { | |
var si_formatter = d3.format(".3s"); | |
var comma_formatter = d3.format(",.3r"); | |
var fixed_formatter = d3.format(",f"); | |
var fixed1_formatter = d3.format(",.1f"); | |
function isInteger(n) { | |
return n === +n && n === (n | 0); | |
} | |
function format_human_readable_number(value) { | |
if (isNaN(value) || value === null) | |
return value; | |
if (value === 0) | |
return 0; | |
var abs_value = Math.abs(value); | |
if (abs_value >= 10000) return si_formatter(value); | |
else if (abs_value >= 100) { | |
if (isInteger(value)) return fixed_formatter(value); | |
else return fixed1_formatter(value); | |
} else if (abs_value >= 0.00005) { | |
if (isInteger(value)) return fixed_formatter(value); | |
else return comma_formatter(value); | |
} else return si_formatter(value); | |
} | |
window.format_human_readable_number = format_human_readable_number; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment