简体   繁体   English

选择数字,然后格式化为小数点后两位

[英]Select number then format to 2 decimal places

I am trying to write some code that will do the following; 我正在尝试编写一些代码来执行以下操作;

  1. Add an ID to nth child 向第n个孩子添加ID
  2. Format the number in nth child to 2 decimal places 将第n个孩子的数字格式设置为2个小数位
  3. Apply £ in front of the numbers 在数字前加上£
  4. Loop until every nth child in a table is done 循环直到表中的第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. 感谢您的所有帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM