Search code examples
javascriptd3.jshandsontable

Scientific Notation in Handsontable


Looking for a way to display scientific notation (12000 = 1.2e+4) with Handsontable v0.33.0

I've found the documentation for formatting numbers in Numbro but it seems geared towards displaying statistics and currency (ie. 1230974 using format: '0.0a' gives 1.2m)

Ideally I'd like the number to be formatted the way d3-format handles this

var value = 1230974
var formattedValue = d3.format(".3")(value)
console.log(formattedValue) // expected value: "1.23e+6"

Solution

  • This is what I came up with following @andy's advice and reading up on Handsontable Custom renderers

    var sensibleNumericRenderer = (hotInstance, td, row, column,
                                   prop, value, cellProperties) => {
      Handsontable.renderers.BaseRenderer.apply(this, arguments);
    
      let prec = 4
      let str
    
      var val = Handsontable.helper.stringify(value)
    
      if(val === "") {
        str = val
      }
      else {
        val = +val //convert to Number
    
        //convert numbers that are too large or too small
        if(val !== 0 && (Math.abs(val) > 1e4 || Math.abs(val) < 1e-2)) {
          //truncate to 4 significant figures then convert to scientific notation
          str = Number.parseFloat(val.toPrecision(prec)).toExponential()
        }
        else {
          // works nicely for small integers or larger decimal fractions
          str = d3.format(`.${prec}`)(val)
        }
      }
      td.innerHTML = str
      return td
    }
    
    Handsontable.renderers.registerRenderer("sensibleNumeric", sensibleNumericRenderer)