D3.js: How to Manage Trailing Zero and Decimal Points in Percentages

Hongtao Hao / 2021-06-07


To remove insignificant trailing zeros, use ~%. For example:

d3.format("~%")(0.010) // "1%"

To have rounded percentages, we need to .0%, .1%, .2%, etc, depending on how many numbers do you want after the percentage sign:

d3.format(".0%")(0.015) // "2%"
d3.format(".1%")(0.015) // "1.5%"
d3.format(".2%")(0.015) // "1.50%"

For more information, please refer to d3-format official documentation .

Last modified on 2021-10-05