Peter
Peter

Reputation: 11825

Javascript - Rounding a number

the result from this function is 5.4 ... but i need 5.40.
It is a simple question but i have no (clean) idea to resolve this.

JS

var test = round(-5.401826873479466,2);

alert(test+' $'); // = 5.4 $

function round(number, decimals) {
    return Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);   
}

FIDDLE http://jsfiddle.net/xMXPz/2/

Upvotes: 0

Views: 69

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382092

Assuming this is for displaying the string, then you need toFixed :

function round(number, decimals) {
   return number.toFixed(decimals)
}

This returns a string. There is no difference, in JS encoding of numbers, between 5.4 and 5.40. Read more in the MDN.

Upvotes: 3

NTK88
NTK88

Reputation: 593

Try this one

var test = round(-5.401826873479466,2);
test=test.toFixed(2);
alert(test+' $');

function round(number, decimals)                                {

return Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);

}

Upvotes: 0

Related Questions