skip to Main Content

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?

2

Answers


  1. 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) + "°");
    
    Login or Signup to reply.
  2. If you have access to this code, you can manipulate is using toFixed on the data itself:

    // If the value is a float
    const to1Decimal = zone.state.sensorDataPoints.insideTemperature.celsius.toFixed(1)
    
    // If the value is a string
    const floatValue = Number.parseFloat(zone.state.sensorDataPoints.insideTemperature.celsius)
    const to1Decimal = floatValue.toFixed(1)
    

    If you don’t you can find this element in the DOM (which will require some more information about the HTML to help you with) and then manipulate it:

    // Assuming we found the node
    const text = elementNode.innerText
    const toFixed1Place = Number.parseFloat(text.split("°")[0]).toFixed(1)
    
    

    See MDN Page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search