[英]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.