I want d3 to format my number to 2 decimal places, only if it has decimal value. Also, I want it to work with one single format function.
For now, I have been using this. Is there any way I can improve this to be able to work around?
d3.format(",.2f")(10101); //10,101.00 which must be displayed as 10,000 only
d3.format(",.2f")(12334.2); //12,334.20 this is okay
I want d3 to format my number to 2 decimal places, only if it has decimal value. Also, I want it to work with one single format function.
For now, I have been using this. Is there any way I can improve this to be able to work around?
d3.format(",.2f")(10101); //10,101.00 which must be displayed as 10,000 only
d3.format(",.2f")(12334.2); //12,334.20 this is okay
Share
Improve this question
edited Jan 28, 2017 at 13:53
Gerardo Furtado
102k9 gold badges128 silver badges176 bronze badges
asked Jan 28, 2017 at 13:37
Sabbiu ShahSabbiu Shah
1,7093 gold badges19 silver badges28 bronze badges
3 Answers
Reset to default 12I want it to work with one single format function
Well, that's not possible. D3 format functions cannot adapt to the number you pass to them like that.
However, you can have two format functions, and test to see if the number you're passing has or has not decimal places. This is one possible way to test:
number % 1
Which returns 0 for integers.
Then, in a ternary operator, you can choose which d3.format
function you'll use:
!(number % 1) ? someFormat(number) : otherFormat(number)
Here is a demo:
var formatInteger = d3.format(",");
var formatDecimal = d3.format(",.2f");
var number1 = 10101;
var number2 = 12334.2;
function format(number){
return !(number % 1) ? formatInteger(number) : formatDecimal(number)
}
console.log(format(number1))
console.log(format(number2))
<script src="https://d3js.org/d3.v4.min.js"></script>
The closest you can get to that is if you use the '~' to remove any trailing zeroes. So in your case, the format would ',.2~f'.
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script>
console.log(d3.format(",.2~f")(10101));
console.log(d3.format(",.2~f")(12334.2));
</script>
More info about d3-format here: https://observablehq.com/@d3/d3-format
You can try this:
const formattedValue = value >= 100000
? value % 1 === 0
? SI(value).replace(".0", "")
: SI(value)
: value