Round up JSON value

Asked

Viewed 190 times

0

In my code, I receive a JSON with a value (Example: 6647), and I would like to round it to just 1 decimal place.

In the code, I take Json’s content by the call:

  render(){
    return(
      <div className="container">
          <div className="row">
                   <div className="col-md-12 col-lg-6 col-xl-3">
                   <div className = "row">
                       <div className = "info-box">
                           <span className = "info-box-icon logo-View">
                           <i className = "fa fa-tasks"> </i> </span>
                           <div className = "info-box-content">
                                 <span className = "info-box-number">{this.state.data.pageViews}</span>
                                 <span className = "info-box-text"> Page Views </span>
                           </div>
                       </div>
                   </div></div>
            </div>

    );
  }

And the class:

 componentDidMount(){
        let URL = 'algumaURL'
           fetch(URL)
           .then(function(response) {
              let data = response.json()
              return data;
           })
           .then((json) => {
              console.log('parsed json', json)
              this.setState({data : json});
           })
           .catch(function(ex) {
              console.log('parsing failed', ex)
           })
  }

JSON:

{"pageViews":13184}

Pageviews value is randomized at each page refresh.

  • How many decimal places by default, two 66,47 or three 6,647?

  • Round to 1 decimal place, 6,647 -> 6,6

1 answer

1

Use the JS function .toFixed():

The method toFixed() format a number using fixed point notation.

Syntax: numObj.toFixed([digits])

Example:

var num = 6.647; 
//O parâmetro da função é o número de casas decimais.
var numeroFormatado = num.toFixed(1);

console.log(numeroFormatado);
/* OBS.:
Se a casa consecutiva a informada no parâmetro
For superior ou igual a 5 o valor será arrendoado para cima.
*/

  • In my JSON, the received number has no separation by comma points (Example: 66557), and if I apply its code, I get this error: Typeerror: Cannot read Property 'toFixed' of Undefined

  • Are you sure the value received is of type number? Because if it is number and has no comma separation, it is not decimal. It is whole, so there is no way to round it up. Put the received JSON template in your question to better understand the problem. The number of decimals of this number is default?

  • added the received json

  • I saw the json and the received value is integer, so your question makes no sense with an integer value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.