Amila
Amila

Reputation: 243

How divide two numbers in java script

I am facing the issue in division of numbers in java script.

Example:

 var x= 2500, var y = 100

 alert(x/y)

is showing 25.

I need the answer in 25.00 format. What can I do?

When I divide 2536/100, it gives as expected.

Upvotes: 2

Views: 41968

Answers (6)

Sandeep Pathak
Sandeep Pathak

Reputation: 10747

You can try number.toFixed(x)

alert( (x/y).toFixed(2) )

Upvotes: 14

Brandon May
Brandon May

Reputation: 23

is it possible to enter x and y as a dollar amount? ie 25.00 and 1.00? if so then use the parseFloat method.

var x = 25.00
var y = 1.00
alert(parseFloat(x/y));

Upvotes: 0

daveoncode
daveoncode

Reputation: 19578

You have to use the toPrecision() method: http://www.w3schools.com/jsref/jsref_toprecision.asp It's a method defined in Number's prototype. If you want to dynamically retrieve a float number with a specific precision (in your case 2), you can do de following:

var x = 2500;
var y = 100;
var res = x/y;
var desiredNumberOfDecimals = 2;
var floatRes = res.toPrecision(String(res).length + desiredNumberOfDecimals);

Upvotes: 3

Hogan
Hogan

Reputation: 70523

Try doing it this way:

    alert((x/y).toFixed(2))

Upvotes: 1

Andreas Eriksson
Andreas Eriksson

Reputation: 9027

var x = 2500;
var y = 100;
alert( (x/y).toFixed(2) );

Upvotes: 0

Bas Slagter
Bas Slagter

Reputation: 9929

You need to take a look at number formatting and decimal precision etc. Look here: http://www.mredkj.com/javascript/nfbasic2.html

Upvotes: -1

Related Questions