15,358,528 members
1.00/5 (1 vote)
See more:
Hello, I need to round the number to an integer value in JavaScript in order to display percentages properly.

What I have tried:

JavaScript
`const calc2=((ebitImpactdkk / this.state.ebitBaseline || 0) * 100).toFixed() + '%'; `

I have tried to do that with a toFixed function and was happy, until I have discovered that it converts the number to a string, while I need it still to be a number.
Posted
Updated 7-Oct-21 2:41am

## Solution 1

Quote:
I need it still to be a number
Why? You're immediately appending a string to it, so even if it was still a number, it would be converted to a string at that point.

If you want to round a number to an integer whilst keeping it as a number, use `Math.round`:
Math.round() - JavaScript | MDN[^]
Member 15341738 7-Oct-21 8:49am

Richard you are right, I guess I can remove the percentage from the input and add it in it's description. But if I change this line to:
const calc2 = (Math.round(ebitImpactdkk / this.state.ebitBaseline ) * 100) || 0;

I am getting either 100, or 0.
Richard Deeming 7-Oct-21 9:02am

Move the `* 100` inside the call to `round`:
`const calc2 = Math.round((ebitImpactdkk / this.state.ebitBaseline  || 0) * 100);`
Member 15341738 7-Oct-21 10:32am

Now it works perfectly, thanks!