Exponential number formatter – javascript

I was looking for a good way to format exponential values that satisfies all of the following…

  • Works in HTML <canvas> elements
  • Has a configurable base value (i.e. 10, 2, e)
  • Shows the exponent as superscript not just 9x10^3
  • Handles negative superscript exponents

The easy solution I found was to use some npm package like numeral.js, and just do something like…

const n = 9000;
const label = numeral(n).format('0[.]00e+0') // 9e+3

Which not terrible for base 10 but when using base 2 or e it isn’t great

numeral(Math.pow(2, 4)).format('0,0e+0') // 2e+1

enter image description here

33 thoughts on “Exponential number formatter – javascript”

Leave a Comment