简体   繁体   English

JS 中的这个切片调用有什么问题?

[英]What's wrong with this slice call in JS?

I write this line but get an error in response:我写了这一行,但收到​​错误响应:

slice can't process there.切片无法在那里处理。

Why and how do I fix that?为什么以及如何解决这个问题?

function (row) {
    var r = Math.round(Object.values(row)[3] / Object.values(row)[4]);
    var t = Object.values(row)[2];
    var s = Math.round((t - r) / t * 100);
    return '<span id="up">${s.slice(0,2)}%</span>'
}

Your variable s is a number but the slice function requires a string .您的变量s是一个数字,但slice函数需要一个string The solution would be to cast s into a string:解决方案是将s转换为字符串:

const slice = `${s}`.slice(0, 2);

Edit编辑

To display a number with n decimals, you can multiply it by 10^n before rounding and then dividing it by the same number, cutting of anything after n decimals.要显示具有n小数的数字,您可以在舍入前乘以10^n ,然后将其除以相同的数字,在n小数后切除任何内容。

// display number with n decimals
const numberDisplay = (number, numberOfDecimals) => Math.round(number * Math.pow(10, numberOfDecimals)) / Math.pow(10, numberOfDecimals);

// your desired number display
const slice = numberDisplay(s, 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM