JS舍入到小数点后两位 [英] JS round to 2 decimal places

查看:100
本文介绍了JS舍入到小数点后两位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将返回的数字限制为仅两位小数,但是此代码对我不起作用;

I am trying to limit the returned number to be only 2 decimal places but this code isn't working for me;

function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "Result is: " + x * 1.09; value = valToRound.toFixed(2);

}

我在做什么错

推荐答案

在JS浏览器控制台中键入

Typing in the JS Browser console

  x = 2.71828
  x.toFixed(2)
  "2.72"

很显然 .toFixed(2)有用

您做错的是四舍五入< 打印答案后,并且未使用正确的变量。

What you did wrong was rounding after printing the answer, and not using the correct variables.

document.getElementById("demo").innerHTML = "Result is: " + x * 1.09; value = valToRound.toFixed(2);

养成将字符串转换为带有<$ c $的数字的习惯也是一个好主意c> parseFloat()。在JS中,除非您先转换为数字,否则'2'*'2'为'4',但'2'+'2'为'22'。

It is also a good idea to get in the habit of converting strings to numbers with parseFloat(). In JS, '2'*'2' is '4' but '2'+'2' is '22', unless you first convert to number.

如果您可以这样操作:

function myFunction() {
  var x = parseFloat(document.getElementById("mySelect").value);
  var valToRound = x * 1.09;
  var value = valToRound.toFixed(2);
  document.getElementByID("demo").innerHTML = "Result is: " + value;
}

这篇关于JS舍入到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆