2

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.

6 Answers 6

14

You can try number.toFixed(x)

alert( (x/y).toFixed(2) )
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

Try doing it this way:

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

Comments

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

Comments

0

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

1 Comment

Welcome to the Stackoverflow. Your answer is not answering the question; Instead, you have changed the question indeed. So, in that case, it's better to tell your opinion/hint as a comment (which you cannot comment right now, cause of your current score). So, Please try to give a related answer, without changing the question conditions (var x= 2500, var y = 100)
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.