Reputation: 167
I have a table and I'm trying to limit the number in a certain cell or column to 2 decimal places.
I've tried the following but it doesn't seem to be changing anything. Any help would be appreciated.
$(".col-product-fee-amount").each(function() {
this.value = parseFloat(this.value).toFixed(2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-product-fee-amount">2.0448</div>
Upvotes: 2
Views: 158
Reputation: 337560
div
elements do not have a value. Instead you need to set their text()
To do that you can provide a function to text()
which accepts the current string as an argument which you can then modify as required and return.
jQuery(function($) {
$(".col-product-fee-amount").text(function(i, text) {
return (parseFloat(text) || 0).toFixed(2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="col-product-fee-amount">2.0448</td>
</tr>
</table>
Note in the above example the use of ||
to coerce an undefined value to a 0
to prevent errors. Also note the document.ready handler wrapping the jQuery logic. This ensures that the DOM has been loaded before you attempt to interact with it
Upvotes: 3
Reputation: 30360
Because you're using JQuery, then that can be achieved by replacing this.value
with this.text()
as shown below:
$(".col-product-fee-amount").each(function(){
$('td').text( parseFloat( $(this).text() ).toFixed(2) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<b>Source data</b>
<div class="col-product-fee-amount">2.0448</div>
<b>Table</b>
<table>
<tr>
<td></td>
</tr>
</table>
Upvotes: 0