之前使用 ExtJS 来格式化数字为百分数。现在我们不再使用 ExtJS,需要使用普通的 JavaScript 完成相同的任务。
需要一个方法,它将接受数字和格式(通常是 %),并将该数字转换为指定格式。
0 -> 0.00% = 0.00%
25 -> 0.00% = 25.00%
50 -> 0.00% = 50.00%
150 -> 0.00% = 150.00%
之前使用 ExtJS 来格式化数字为百分数。现在我们不再使用 ExtJS,需要使用普通的 JavaScript 完成相同的任务。
需要一个方法,它将接受数字和格式(通常是 %),并将该数字转换为指定格式。
0 -> 0.00% = 0.00%
25 -> 0.00% = 25.00%
50 -> 0.00% = 50.00%
150 -> 0.00% = 150.00%
您可以使用 Number.toLocaleString() 方法:
var num=25;
var s = Number(num/100).toLocaleString(undefined,{style: 'percent', minimumFractionDigits:2});
console.log(s);
25.00%
参见toLocaleString()文档,以获取格式对象参数的更多选项。
以下是您所需要的内容。
var x=150;
console.log(parseFloat(x).toFixed(2)+"%");
x=0;
console.log(parseFloat(x).toFixed(2)+"%");
x=10
console.log(parseFloat(x).toFixed(2)+"%");
对于任何一个,如果您是从整数开始而不是小数,请删除* 100
。
基础知识:
const displayPercent = (percent) => `${(percent * 100).toFixed(2)}%`;
const displayPercent = (percent, fallback, digits = 2) =>
(percent === null || percent === undefined) ? fallback : `${(percent * 100).toFixed(digits)}%`;
const displayPercent = (percent: number) => `${(percent * 100).toFixed(2)}%`;
我有一些十进制值,例如0.01235
和0.016858542
,我想将它们转换为百分比1.235%和1.6858542%。我以为这很容易,只需计算(0.012858542 * 100)
就可以了。但我错了,(0.012858542 * 100) = 1.2858542000000002
,因为存在十进制转换问题。
让我们在计算中添加toFixed()
,然后我就得到了正确的值。
(0.012858542*100).toFixed(7) // returns "1.2858542"
(0.01235*100).toFixed(7) // returns "1.2350000"
我不喜欢在不必要的情况下显示四个尾随零。我想到的一个解决方案是使用{{link1:replace()
}}来删除所有尾随零,但最终我使用了Numeral.js,因为它可以在轻量级的同时为我完成所有工作。我可以推荐它!
import numeral from 'numeral';
numeral(0.012858542 * 100).format('0.00[0000]') // returns "1.2858542"
numeral(0.01235 * 100).format('0.00[0000]') // returns "1.235"
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction(num) {
number = num.toString();;
console.log(number)
var words2 = number.split(".");
for (var i = 0; i < words2.length; i++) {
words2[i] += " ";
}
num1 = words2[0];
num2 = words2[1];
num1 = num1.trim();
if(num2==undefined){
number1 = num1+'.00%';
return number1;
}else{
num2 = num2.trim();
number1 = num1+'.'+num2+'%';
return number1;
}
}
document.getElementById("demo").innerHTML = myFunction(50.12);
</script>
</body>
</html>
将数字转换为带有X个小数位的百分比
function toPercent(number, float) {
var percent = parseFloat(number * 100).toFixed(float) + "%";
return percent;
}
toLocaleString
的浏览器兼容性 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Browser_compatibility. - Gokhan Sari