Reputation: 43
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
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
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
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