Javascript 如何在java脚本中划分两个数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8007658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:22:19  来源:igfitidea点击:

How divide two numbers in java script

javascriptnumbersdivide

提问by Amila

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

我在java脚本中面临数字划分的问题。

Example:

例子:

 var x= 2500, var y = 100

 alert(x/y)

is showing 25.

显示 25。

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

我需要25.00格式的答案 。我能做什么?

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

当我除以 2536/100 时,它按预期给出。

回答by Sandeep Pathak

You can try number.toFixed(x)

你可以试试number.toFixed(x)

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

回答by daveoncode

You have to use the toPrecision() method: http://www.w3schools.com/jsref/jsref_toprecision.aspIt'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:

您必须使用 toPrecision() 方法:http://www.w3schools.com/jsref/jsref_toprecision.asp这是在 Number 的原型中定义的方法。如果要动态检索具有特定精度的浮点数(在您的情况 2 中),您可以执行以下操作:

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

回答by Hogan

Try doing it this way:

尝试这样做:

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

回答by Andreas Eriksson

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

回答by Brandon May

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.

是否可以输入 x 和 y 作为美元金额?即 25.00 和 1.00?如果是,则使用 parseFloat 方法。

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

回答by Bas Slagter

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

你需要看看数字格式和小数精度等。看看这里:http: //www.mredkj.com/javascript/nfbasic2.html