【问题标题】:showing the exact decimal (not rounding) javascritp / jquery显示精确的小数(不四舍五入)javascript / jquery
【发布时间】:2021-06-25 05:24:19
【问题描述】:

我想要的只是在“。”之后显示一个只有一个数字的变量的结果。 我试过 toFixedtoPrecision 但它们是整数,我希望结果准确 在:

var result = 6.853571428571428; //
$("#id").html(result); //want to show 6.8

我只想显示“6.8”,使用 toFixed(2)toPrecision(2) 等函数给我 6.9。 也尝试过Math.round(number * 10) / 10,但结果相同

【问题讨论】:

  • 我已经试过了,即使在示例中,它们也将 15.7784514 舍入到 17.8,我只想得到“。”之后的第一个数字,在你给我的示例中应该是 17.7而不是 17.8 :)
  • 只需稍微调整答案中的正则表达式var with1Decimals = num.toString().match(/^-?\d+(?:\.\d{0,1})?/)[0]jsfiddle.net/xeqfb2vd

标签: javascript jquery decimal


【解决方案1】:
var result = 6.853571428571428;
$("#id").html(Math.trunc(result*10)/10);

【讨论】:

  • 这比我的眼睛漂亮多了! $("#id").html((+((""+(result*10)).split('.')[0])/10)) - 感谢分享。我不知道Math.trunc
【解决方案2】:

check other and complete solutions here

    var result = 6.853571428571428; 
    result = result.toString(); //pars it to String 
    result = result.slice(0, (result.indexOf("."))+2);
    console.log(Number(result));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    相关资源
    最近更新 更多