1

I am trying to write some code that will do the following;

  1. Add an ID to nth child
  2. Format the number in nth child to 2 decimal places
  3. Apply £ in front of the numbers
  4. Loop until every nth child in a table is done

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.

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.

zoro724
  • 87
  • 3
  • 13

1 Answers1

1

To round a number to n decimal places:

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
Don McCurdy
  • 10,975
  • 2
  • 37
  • 75
  • Hey Thanks for this, How do i go about making var number dynamic rather than defining a number? like var number = #test or something im having no luck on this end doing this Thanks again. – zoro724 May 08 '15 at 19:13
  • Sure thing, you probably just want to make a new function in that case. Updated the answer. – Don McCurdy May 09 '15 at 20:00