【问题标题】:Rounding a variable to the nearest integer将变量四舍五入为最接近的整数
【发布时间】:2017-02-18 19:17:34
【问题描述】:

我有一些代码可以将变量四舍五入到最接近的整数 - 除了我似乎无法让它将变量四舍五入到最接近的整数。这是我的代码:

var score = 600;
var coinBase = 400;
var coinInt = score / coinBase;
var coin = round(VARIABLEcoinInt');

换句话说,我正在尝试获取变量 coinInt,将其四舍五入到最接近的整数,然后将其输出到变量 coin。

【问题讨论】:

  • 在过去,你必须加一半并取一个整数。
  • 使用Math.round()函数
  • 首先,round 不是有效的Javascript 方法。其次round(VARIABLEcoinInt') 是无效的语法。第三VARIABLEcoinInt不是定义变量

标签: javascript variables rounding


【解决方案1】:

没有round 函数。请改用Math.round 函数。

var score = 600;
var coinBase = 400;
var coinInt = score / coinBase;
var coin = Math.round(coinInt);

console.log(coin);

【讨论】:

    【解决方案2】:

    您可以使用 3 个基于 Math 的函数之一。

    Math.round - 四舍五入到最接近的整数:

    Math.round(1.4) // 1
    Math.round(1.5) // 2
    

    Math.floor - 向下舍入

    Math.floor(1.2) // 1
    Math.floor(1.9) // 1
    

    Math.ceil - 向上取整

    Math.ceil(1.2) // 2
    Math.ceil(1.9) // 2
    

    【讨论】:

      猜你喜欢
      • 2011-03-21
      • 1970-01-01
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      相关资源
      最近更新 更多