开发者

Multiply numbers with more than 4 decimal points [duplicate]

This question already has answers here: 开发者_如何学编程 Closed 11 years ago.

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!


You can use .toFixed

var number = 0.365999999999999;    
var rounded = number.toFixed(4);  // 0.3660


try this:

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

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

   var total = number*current;

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

});


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


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.


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);


$("#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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜