I am trying to write some code that will do the following;
我正在尝试编写一些代码来执行以下操作;
- Add an ID to nth child
- Format the number in nth child to 2 decimal places
- Apply £ in front of the numbers
- Loop until every nth child in a table is done
为第n个孩子添加ID
将第n个孩子的数字格式化为2个小数位
在数字前面应用£
循环直到表中的每个第n个孩子都完成
I have numbers such as this to round of “0.7823076923076923” using the code I have I can get it to round up to "1" but I need it to round to 0.78 I then added “toFixed(2)” and it takes my “1” and puts it to “1.00” but I need It to go to “0.78” once I have that in place I can then look at how I can loop the code, but small steps.
我有这样的数字到圆形“0.7823076923076923”使用我有的代码我可以得到它向上舍入到“1”但我需要它来舍入到0.78我然后添加“toFixed(2)”它需要我的“ 1“并将其置于”1.00“但我需要它到”0.78“一旦我有了它,我可以看看如何循环代码,但小步骤。
Thanks for all the help.
谢谢你的帮助。
Code:
<script>
$(document).ready(function(){
$('table>tbody>tr>td:nth-child(5n)').prop('id', 'test');
$('#test').text(function(i,v) {
return Math.round(parseInt(v * 100) / 100).toFixed(2);
});
});
</script>
UPDATE i got it working!!!
更新我让它工作!
$(document).ready(function(){
$('table>tbody>tr>td:nth-child(5n)').prop('id', 'test');
var test = parseFloat($('#test').text()).toFixed(2);
$('table>tbody>tr>td:nth-child(5n)').empty().append(test);
});
now to make it loop,
现在让它循环,
Thanks for all the help.
谢谢你的帮助。
1 个解决方案
#1
To round a number to n
decimal places:
要将数字舍入到n个小数位:
var n = 2;
var number = 0.7823076923076923;
var result = Math.round(number * Math.pow(10,n)) / Math.pow(10,n);
result = result.toFixed(n);
UPDATE:
For a more reusable option, you can define a custom rounding function:
对于更可重用的选项,您可以定义自定义舍入功能:
function roundTo (value, n) {
var result = Math.round(value * Math.pow(10,n)) / Math.pow(10,n);
return result.toFixed(n);
}
var foo = roundTo(0.7823076923076923, 2); // 0.78
#1
To round a number to n
decimal places:
要将数字舍入到n个小数位:
var n = 2;
var number = 0.7823076923076923;
var result = Math.round(number * Math.pow(10,n)) / Math.pow(10,n);
result = result.toFixed(n);
UPDATE:
For a more reusable option, you can define a custom rounding function:
对于更可重用的选项,您可以定义自定义舍入功能:
function roundTo (value, n) {
var result = Math.round(value * Math.pow(10,n)) / Math.pow(10,n);
return result.toFixed(n);
}
var foo = roundTo(0.7823076923076923, 2); // 0.78