【问题标题】:Why do I have type 'never' on my decimal?为什么我的小数点上输入“从不”?
【发布时间】:2022-01-06 19:57:28
【问题描述】:

我正在尝试编写将数字四舍五入到最接近的百分之一的代码,但如果它只到十分位,它会添加一个零。

由于某种原因,我的代码显示我的小数点类型为“从不”。有什么解决办法吗?

newCost 是我的小数。成本变量是我的显示器。

let newCost =
   Math.round(
     (parseFloat(cost.textContent) + parseFloat(this.state.price)) *
     1.1 *
     100
   ) / 100;
if (typeof newCost === "float" && typeof newCost * 10 === "int") {
  cost.textContent = newCost.toString().concat("0");
} else {
  cost.textContent = newCost;
}

【问题讨论】:

  • 我不明白你通过阅读你的第一段想要达到什么目的。你能添加一些示例输入和输出吗?

标签: reactjs types typeerror


【解决方案1】:

您可以使用toFixed

let newCost = ((cost.textContent + this.state.price) * 1.1).toFixed(2);

如果小数是 2 位数字,它只需要它们。如果没有,那么它会自动在末尾附加0

【讨论】:

    【解决方案2】:

    typeof 运算符永远不能输出"float""int";所有数字的结果都是"number"。因此,无法输入if 语句。由于这是不可能的,打字稿通过将newCost 上的类型缩小到never 来表明这一点。

    更改代码的一种可能方法是使用Number.isInteger

    if (!Number.isInteger(newCost) && Number.isInteger(newCost * 10))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      相关资源
      最近更新 更多