Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round to 2 decimal places in jquery datatable?

I am using jquery datatable aocolumns to round the specific columns to two decimal places but it seems like i am unable to get the correct regular expression for this or may be their is something wrong with my logic.

"aoColumnDefs": [ {
                        "aTargets": [ 7 ],
                        "mRender": function (data, type, full) {
                            var formmatedvalue = data.replace(/\d+(\.\d{1,2})?/, "")
                             return formmatedvalue;
                        }
                    }],

The output for that column should be

120.02
1560.56
565645.25
124995.89
etc .....

Any possible solution for this?

like image 475
lokopi Avatar asked Sep 21 '15 06:09

lokopi


People also ask

How to round off numbers with two or more decimal places using jQuery?

Here I will explain how to use jQuery to round off numbers to two or 2 decimal places example using JavaScript toFixed () or toPrecision () functions or jQuery round off number with two or more decimal values using JavaScript toFixed () or toPrecision () functions.

How do I read decimal numbers in DataTables?

When reading such numbers, Javascript won't automatically recognise them as numbers, however, DataTables' type detection and sorting methods can be instructed through the language.decimal option which character is used as the decimal place in your numbers.

How do you round to 2 decimal places?

I've been using some code which basically multiplies by 100, rounds using Math.round() and divides by 100 to get 2 decimal places. This is incredibly simple instead. Thanks. September 2, 2011 at 2:50 AM

How to round to the nearest integer value in JavaScript?

The Math.round() method is used to round to the nearest integer value. It takes number which needs to be rounded off as an input.


2 Answers

For decimal places upto 2 you can use the following code in datatable

 function (data, type, full) {
         return parseFloat(data).toFixed(2);
    }
like image 83
Mohammed Irfan Tirupattur Avatar answered Sep 22 '22 14:09

Mohammed Irfan Tirupattur


Use this function:

function (data, type, full) {
     return data.toString().match(/\d+(\.\d{1,2})?/g)[0];
}

You would be looking for matching the part you need and not to replace.

like image 43
James Jithin Avatar answered Sep 21 '22 14:09

James Jithin