【问题标题】:Is there a way to cut off a part of a decimal in Javascript?有没有办法在Javascript中切断小数的一部分?
【发布时间】:2019-10-20 14:21:48
【问题描述】:

我有一个通过加法每秒增加的数字。问题是它包含太多的小数。我不想要的输出示例是 1.5999999999999999 或 1.600000000001。我尝试使用 toFixed 方法,传入 2 作为它的值,但我仍然遇到问题。我也尝试过使用 Math.round(number * 100) / 100 并且仍然得到丑陋的小数。 如何获得仅包含指定小数点数的输出?我希望能够选择数字的舍入方式。舍入的函数应该是这样的:

function round(numberToRound, afterDecimals){
//Rounding code which takes into the account the number of decimal values I wish to display should go here
}

谢谢。

【问题讨论】:

  • toFixed 可以。您一定没有正确应用它。
  • 是的,请张贴代码显示您如何尝试使用toFixed
  • 确实,toFixed 应该这样做。您能告诉我们您是如何尝试使用toFixed 对您的数字进行四舍五入的吗?
  • function rnd(num1, num2) { return num1.toFixed(num2); }//cf rnd(6.38473829, 2);
  • 这有什么问题?你需要numberrnd 返回string 吗?

标签: javascript numbers decimal


【解决方案1】:

非常抱歉,我没有在正确的位置调用该函数。该功能按预期工作,我只是没有正确更新 innerHTML。 再次抱歉,我忽略了这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多