Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round off to 2 decimal places with format SI prefix?

Example in my case:

d3.format("~s")(656628); //656.628k

But my expected result: 656.63k

I would like used option of d3-format instead of handling it manually.

Live test: https://npm.runkit.com/d3-format

like image 704
thienshaman Avatar asked Apr 10 '19 08:04

thienshaman


Video Answer


1 Answers

All you need is d3.formatPrefix, which...

Convert values to the units of the appropriate SI prefix for the specified numeric reference value before formatting in fixed point notation.

..., with ".2" as the specifier and your own number as the value.

Here is the demo with your number:

const myNumber = 656628;
console.log(d3.formatPrefix(".2", myNumber)(myNumber));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

That gives you your expected result: 656.63k.

And, for completeness, some other numbers as well:

[1232, 7676546655, 665, 0.0012, 8887878].forEach(function(d) {
  console.log("Number: " + d + " - Your format: " + d3.formatPrefix(".2", d)(d))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
like image 86
Gerardo Furtado Avatar answered Oct 05 '22 23:10

Gerardo Furtado