Sabbiu Shah
Sabbiu Shah

Reputation: 1709

Format number to 2 decimal places only if it has decimal places

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

Upvotes: 3

Views: 8737

Answers (3)

Sridhar Sg
Sridhar Sg

Reputation: 1596

You can try this:


const formattedValue = value >= 100000
                ? value % 1 === 0
                  ? SI(value).replace(".0", "")
                  : SI(value)
                : value

Upvotes: 0

Xaquín G.V.
Xaquín G.V.

Reputation: 71

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

Upvotes: 7

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

I 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>

Upvotes: 12

Related Questions