user2064285
user2064285

Reputation: 43

Rounding decimal in a table in jQuery

I dont know if its possible to ask a question here, that i really dont have a clue how to fix

How do i round all numbers in this table to only show 1 decimal with jquery ?

<table>
  <tr>
    <th>2012</th>
    <th>2013</th>
    <th>2014</th>
    <th>2015</th>
    <th>2016</th>
  </tr>
  <tr>
    <td>2.53</td>
    <td>2.56</td>
    <td>7.45</td>
    <td>54.32</td>
    <td>2.534</td>
  </tr>
  <tr>
    <td>54.43</td>
    <td>26.24</td>
    <td>33.65</td>
    <td>33.65</td>
    <td>2.53</td>
  </tr>
  <tr>
    <td>33.56</td>
    <td>46.23</td>
    <td>33.65</td>
    <td>24.76</td>
    <td>3.65</td>
  </tr>
</table>

Upvotes: 0

Views: 643

Answers (3)

Sumit Bhattarai
Sumit Bhattarai

Reputation: 308

If I am correct to understand your question for rounding to 1 decimal do like below example:

    var num = 54.5678;
    var n = num.toFixed(1);
    alert(n);

Above code will generate 54.6 you can do like this in your code.

Upvotes: 0

Farhad Bagherlo
Farhad Bagherlo

Reputation: 6699

$("td").map(function(){
   $(this).text(Number.parseFloat($(this).text()).toFixed(1));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>2012</th>
    <th>2013</th>
    <th>2014</th>
    <th>2015</th>
    <th>2016</th>
  </tr>
  <tr>
    <td>2.53</td>
    <td>2.56</td>
    <td>7.45</td>
    <td>54.32</td>
    <td>2.534</td>
  </tr>
  <tr>
    <td>54.43</td>
    <td>26.24</td>
    <td>33.65</td>
    <td>33.65</td>
    <td>2.53</td>
  </tr>
  <tr>
    <td>33.56</td>
    <td>46.23</td>
    <td>33.65</td>
    <td>24.76</td>
    <td>3.65</td>
  </tr>
</table>

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

Replace comma with . and use toFixed(1)

$( "td" ).each( function(){
  var value = $(this).text();
  value = Number(value.replace(/,/, "." )).toFixed(1);
  $(this).text( value );
});

Demo

$( "td" ).each( function(){
  var value = $(this).text();
  value = Number(value.replace(/,/, "." )).toFixed(1);
  $(this).text( value );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>2012</th>
    <th>2013</th>
    <th>2014</th>
    <th>2015</th>
    <th>2016</th>
  </tr>
  <tr>
    <td>2,53</td>
    <td>2,56</td>
    <td>7,45</td>
    <td>54,32</td>
    <td>2,534</td>
  </tr>
  <tr>
    <td>54,43</td>
    <td>26,24</td>
    <td>33,65</td>
    <td>33,65</td>
    <td>2,53</td>
  </tr>
  <tr>
    <td>33,56</td>
    <td>46,23</td>
    <td>33,65</td>
    <td>24,76</td>
    <td>3,65</td>
  </tr>
</table>

Edit

Since you only have the decimal now, so just use toFixed(1) after converting the value to number

$( "td" ).each( function(){
  var value = $(this).text();
  value = Number(value).toFixed(1);
  $(this).text( value );
});

Upvotes: 1

Related Questions