Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
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

1 solution

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[^]
 
Share this answer
 
Comments
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!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900