Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display rounded number in a span in JS

A tool that I am using is displaying a room temperature on a smart mirror. This line of code is creating the temperature value:

var temperatureTextWrapper = document.createTextNode(
   zone.state.sensorDataPoints.insideTemperature.celsius + "°"
);

After this the var is just being appended to an existing span.
By default, the value contains two decimal places eg. 25.76°C. However I would love to have it rounded to one decimal place or even full integers.

I already tried the .replace() or .slice() functions but with no success. What’s the best way to approach this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Math.round() to round to the nearest integer.

var temperature = 25.76;

// Nearest integer
console.log( Math.round(temperature) )

// One decimal place
console.log( Math.round(temperature*10)/10 )

In your case, you could use:

var temperature = zone.state.sensorDataPoints.insideTemperature.celsius;

var temperatureTextWrapper = document.createTextNode(Math.round(temperature) + "°");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading