[英]Making a thousands (k) convertor function in Javascript without rounding and NOT remove .0 from end
I am trying to make a simple 1000 to k convertor function in JS that will take a number and convert it into thousands/k.我正在尝试在 JS 中制作一个简单的 1000 到 k 转换器 function ,它将接受一个数字并将其转换为千/千。 I'm having trouble getting the.toFixed(1) working properly.我无法让 the.toFixed(1) 正常工作。 I don't want it to round up and I want it to show one decimal place UNLESS that decimal is a 0. A few examples of the returns I am looking to produce are:我不希望它四舍五入,我希望它显示一位小数,除非小数是 0。我希望产生的回报的几个例子是:
1100 -> 1.1K 1100 -> 1.1K
1199 -> 1.1K 1199 -> 1.1K
9999 -> 9.9K 9999 -> 9.9K
10900 -> 10.9K 10900 -> 10.9K
10999 -> 10.9K 10999 -> 10.9K
JS JS
function kConvertor(num) {
return num <= 999 ? num : (num/1000).toFixed(1) + 'k'
}
This returns 10.0k which hits both cases that I do not want (9.9k).这将返回 10.0k,这两种情况我都不想要(9.9k)。 What am I doing wrong here?我在这里做错了什么?
I tried adding a parseInt() and.replace('.0', '') to the end and that didn't work.我尝试在末尾添加一个 parseInt() 和 .replace('.0', '') ,但这没有用。
function kConvertor(num) {
return num <= 999 ? num : parseInt((num/1000)).toFixed(1).replace('.0', '') + 'k'
}
This just returns 9k这只是返回 9k
This works by using math operators to correctly round down to the nearest 10th of a K, and then uses .toFixed(1)
to perform the string manipulation necessary to strip .0
from the result:这通过使用数学运算符正确向下舍入到最接近的 10 个 K,然后使用.toFixed(1)
执行从结果中去除.0
所需的字符串操作:
function kConverter(num) {
return num <= 999 ? num : (0.1 * Math.floor(num / 100)).toFixed(1).replace('.0','') + 'k'
}
NB: it's not good practise to have the function return a number for <= 999, or a string otherwise.注意:让 function 返回一个 <= 999 的数字或其他字符串不是一个好习惯。 Unexpected result types is the cause of the vast majority of the "WAT?!"意外的结果类型是绝大多数“WAT?!”的原因。 moments from the famous video .著名视频的瞬间。 Always ensure that your return types are consistent:始终确保您的返回类型是一致的:
function kConverter(num) {
if (num < 1000) {
return number.toFixed(0); // assuming an integer
} else {
const s = (0.1 * Math.floor(num / 100)).toFixed(1);
return s.replace('.0', '') + 'k';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.