yogeshbdahe
yogeshbdahe

Reputation: 21

how to round up the numbers in javascript

I want to round up a number to 2 decimal places, such as 312.12.

Here is my code which doesn't work correctly. Could you please suggest what I am doing wrong.

(document.getElementById("AmtReturn").value = valAmtRefund*valConvRate;) 
   function populateAmtReturned(){
        var valConvRate = document.getElementById("convRate").value;
        var valAmtRefund = document.getElementById("AmtRefund").value;
        var valAmtReturn = document.getElementById("AmtReturn").value;
    if(!(valAmtRefund.length >0))
        {
            ShowErrorEx('AmtRefund','Amount Refunded');
            return false;
        }
    if(valConvRate.length > 0 )
    {
        if (ValidateConvsionEx('convRate',true,'conversion rate'))
        {
            document.getElementById("AmtReturn").value =valAmtRefund*valConvRate;           
        }
    }
} 

Upvotes: 1

Views: 2007

Answers (4)

David Hellsing
David Hellsing

Reputation: 108500

Use Math.round for rounding. Use Math.ceil for rounding up. Use Math.floor for rounding down.

Or use .toFixed() if you just want to strip out the decimals:

var num = 12.43;
num.toFixed(); // 12

Note that .toFixed() returns a string, not number.

Upvotes: 5

Yoshi
Yoshi

Reputation: 54649

ref: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed

312.123456.toFixed(2);  // "312.12"

Upvotes: 1

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

If you need to round to two digits and always round up do

var original=28.453

var result=Math.ceil(original*100)/100 

Upvotes: 1

Simon Edström
Simon Edström

Reputation: 6619

If you just have a decimal number and want to round it use Math.round(number)

Math.round(2.1) // Will return true

Upvotes: 0

Related Questions