Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omitting trailing zeroes / using sigfigs with d3.format()

I am using d3 indirectly via Plotly and need to pass down a formatting string for numbers on the axis.

I'm having a hard time getting the effect described in this PR to work. https://github.com/d3/d3-format/pull/57

The syntax described in the PR isn't in the documentation https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md#d3_format

Basically - is there a way to get rid of these trailing zeroes? I need to properly display arbitrarily small numbers (e.g. 0.00123), so simple truncation won't work - I need a true sigfig method that omits trailing zeroes

format = ".5g"
f = d3.format(format);
f(0.00123)           ==> 0.0012300 ☹
f(40)                ==> 40.000  ☹
f(5180.159999999996) ==> 5180.2 🙂
f(999999)            ==> 1.0000e+6 🙂

trailing zeroes from d3.js

like image 935
Doug Denniston Avatar asked Mar 24 '26 06:03

Doug Denniston


1 Answers

You are missing the flag ('~') in your format to remove the trailing zeroes. This seems to work...

format = ".5~g"
f = d3.format(format)
console.log(f(0.00123))
console.log(f(40))
console.log(f(5180.159999999996))
console.log(f(999999))
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
like image 88
mdml Avatar answered Mar 26 '26 01:03

mdml