将数字设为百分比

use*_*259 92 javascript math

什么是从数字中删除"0."XXX%的最佳方法并将其设为百分比?如果数字恰好是int会怎么样?

var number1 = 4.954848;
var number2 = 5.9797;

$(document).ready(function() {    
    final = number1/number2;
    alert(final.toFixed(2) + "%");
});
Run Code Online (Sandbox Code Playgroud)

Nea*_*eal 186

百分比只是:

(number_one / number_two) * 100
Run Code Online (Sandbox Code Playgroud)

不需要任何花哨的东西:

var number1 = 4.954848;
var number2 = 5.9797;

alert(Math.floor((number1 / number2) * 100)); //w00t!
Run Code Online (Sandbox Code Playgroud)

  • 保持pct十进制:var pct =(num*100).toFixed(1)+"%"; (47认同)
  • @nyxz Ugg--你为人类而不是机器编写代码.除非你处于某种超紧密的循环中,否则`~~`的可读性远远低于`Math.floor` (8认同)
  • 警报(~~((number1/number2)*100)); 因为Math.floor慢于~~ :) (5认同)
  • 没理由我知道.无论如何,83%的百分比都是弥补的 (5认同)
  • 为什么是`Math.floor`?而不是`Math.round`?即使在您的示例中,“4.954848 / 5.9797”也更接近“83%”而不是“82%”您的代码输出。 (2认同)

xtr*_*rem 55

((portion/total) * 100).toFixed(2) + '%'
Run Code Online (Sandbox Code Playgroud)


Lir*_*ira 30

最好的解决方案en是英语语言环境:

fraction.toLocaleString("en", {style: "percent"})

  • @slorenzo 要获得十进制数字,您可以尝试类似`fraction.toLocaleString("en", { style: "percent", minimumFractionDigits: 2 })` 见/sf/answers/2084140481/ (3认同)
  • @slorenzo 9.23实际上是923%。假设您想要9.23%,则需要将9.23除以100,然后尝试进行转换。 (2认同)

Ale*_*pin 16

好吧,如果你有一个这样的数字0.123456是除法给出一个百分比的结果,将它乘以100,然后将其四舍五入或toFixed在你的例子中使用.

Math.round(0.123456 * 100) //12
Run Code Online (Sandbox Code Playgroud)

这是一个jQuery插件来做到这一点:

jQuery.extend({
    percentage: function(a, b) {
        return Math.round((a / b) * 100);
    }
});
Run Code Online (Sandbox Code Playgroud)

用法:

alert($.percentage(6, 10));
Run Code Online (Sandbox Code Playgroud)

  • `jQuery.round`和`jQuery.divide`和`jQuery.multiply`在哪里? (15认同)
  • @ Xeon06嗯,OP似乎已经改变了主意.奇怪的.我的答案**没有足够的jQuery. (2认同)
  • @Raynos我开始使用循环和使用字符串操作的循环进行乘法,但我放弃了除法. (2认同)