Javascript 将数字设为百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8522673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make a number a percentage
提问by user1040259
What's the best way to strip the "0."XXX% off a number and make it a percentage? What happens if the number happens to be an int?
去除数字的“0.”XXX% 并将其设为百分比的最佳方法是什么?如果数字恰好是 int 会发生什么?
var number1 = 4.954848;
var number2 = 5.9797;
$(document).ready(function() {
final = number1/number2;
alert(final.toFixed(2) + "%");
});
回答by Naftali aka Neal
A percentage is just:
百分比只是:
(number_one / number_two) * 100
No need for anything fancy:
不需要任何花哨的东西:
var number1 = 4.954848;
var number2 = 5.9797;
alert(Math.floor((number1 / number2) * 100)); //w00t!
回答by xtrem
((portion/total) * 100).toFixed(2) + '%'
回答by Liron Shapira
The best solution, where en
is the English locale:
最好的解决方案,en
英语语言环境在哪里:
fraction.toLocaleString("en", {style: "percent"})
fraction.toLocaleString("en", {style: "percent"})
回答by Alex Turpin
Well, if you have a number like 0.123456
that is the result of a division to give a percentage, multiply it by 100 and then either round it or use toFixed
like in your example.
好吧,如果你有一个像0.123456
这样的数字是除以百分比的结果,请将其乘以 100,然后将其四舍五入或toFixed
在您的示例中使用。
Math.round(0.123456 * 100) //12
Here is a jQuery plugin to do that:
这是一个 jQuery 插件来做到这一点:
jQuery.extend({
percentage: function(a, b) {
return Math.round((a / b) * 100);
}
});
Usage:
用法:
alert($.percentage(6, 10));
回答by adamwdraper
Numeral.jsis a library I created that can can format numbers, currency, percentages and has support for localization.
Numeral.js是我创建的一个库,它可以格式化数字、货币、百分比并支持本地化。
numeral(0.7523).format('0%') // returns string "75%"
numeral(0.7523).format('0%') // returns string "75%"
回答by Tomas Kubes
var percent = Math.floor(100 * number1 / number2 - 100) + ' %';
var百分比 = Math.floor(100 * number1 / number2 - 100) + '%';
回答by StangSpree
Most answers suggest appending '%' at the end. I would rather prefer Intl.NumberFormat()
with { style: 'percent'}
大多数答案建议在末尾附加 '%'。我宁愿Intl.NumberFormat()
与{ style: 'percent'}
var num = 25;
var option = {
style: 'percent'
};
var formatter = new Intl.NumberFormat("en-US", option);
var percentFormat = formatter.format(num / 100);
console.log(percentFormat);
回答by Scott Ming
@xtrem's answer is good, but I think the toFixed
and the makePercentage
are common use. Define two functions, and we can use that at everywhere.
@xtrem 的回答很好,但我认为 thetoFixed
和 themakePercentage
很常见。定义两个函数,我们可以在任何地方使用它。
const R = require('ramda')
const RA = require('ramda-adjunct')
const fix = R.invoker(1, 'toFixed')(2)
const makePercentage = R.when(
RA.isNotNil,
R.compose(R.flip(R.concat)('%'), fix, R.multiply(100)),
)
let a = 0.9988
let b = null
makePercentage(b) // -> null
makePercentage(a) // -> ?????99.88%?????