1

Possible Duplicate:
round number in JavaScript to N decimal places

This may be easy for you guys,

My question is:

How can I control a decimal places in a floating point value.

Ex.: My result is returning 0.365999999999999; but I need to show just 4 decimal numbers.

Check the demo: Demo (I accept any others ways to calculate that)

Thanks!

Community
  • 1
  • 1
Ricardo Binns
  • 3,228
  • 6
  • 44
  • 71
  • 1
    Entering `javascript round to 4 decimal places` in the search box on the top right of the page brought up [round number in JavaScript to N decimal places](http://stackoverflow.com/questions/2221167/round-number-in-javascript-to-n-decimal-places), among others. Please research before posting. – Frédéric Hamidi Jun 30 '11 at 17:12

7 Answers7

4

You can use .toFixed

var number = 0.365999999999999;    
var rounded = number.toFixed(4);  // 0.3660
rosscj2533
  • 9,195
  • 7
  • 39
  • 56
2

try this:

$("#test").keyup(function(){

   var number = parseFloat($("#number").text());
   var current = parseFloat($(this).val());

   var total = number*current;

   $("#result").val(total.toFixed(4));

});
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
1
$("#result").val(total.toFixed(4));
kei
  • 20,157
  • 2
  • 35
  • 62
1

Javascript has a nice round function, but it only does integers so you have to multiply it by 10000 then divide the rounded result by 10000

http://www.javascriptkit.com/javatutors/round.shtml

The toFixed function always rounds up, but round will probably do what you want.

Chriszuma
  • 4,464
  • 22
  • 19
0

For proper rounding:

    function roundNumber(number, digits) {
        var multiple = Math.pow(10, digits);
        var rndedNum = Math.round(number * multiple) / multiple;
        return rndedNum;
    }

For rounding up:

number.toFixed(4);
Marino Šimić
  • 7,318
  • 1
  • 31
  • 61
0
$("#test").keyup(function(){

   var number = $("#number").text();
   var current = $(this).val();

   var total = parseFloat(number*current).toFixed(2);

   $("#result").val(total);

});

Cast the variable to a float and then use the toFixed() method

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

If you follow the link below you can import the number_format php function to javascript. The function has been helping me for years now.

Here is the function signature :

function number_format (number, decimals, dec_point, thousands_sep)

http://phpjs.org/functions/number_format:481

David Laberge
  • 15,435
  • 14
  • 53
  • 83