0

Sorry for asking this question, I didn't pay attention in school...

Say I have two numbers: 3 and 7

I'd like to create a bar that shows the percentage of both numbers (out of 100%) in other words, calculate those numbers, so the bar shows: IIIXXXXXXX

I hope I make sense.. thanks in advance.

4

3 回答 3

1

我认为您的意思是您希望条形图将 3 和 7 显示为相对值,每个值都占整体的适当百分比

IIIXXXXXXX

计算很简单:

var total = 3 + 7;
var percentA = 3 / total; // 30%
var percentB = 7 / total; // 70%

每个组件的宽度是条形总宽度乘以所选值并除以值的总和。

因此,如果条形图应该是 100 像素,您将计算两个组件的宽度,例如

var widthA = 100 * ( A / (A+B) );
var widthB = 100 * ( B / (A+B) );

100 * ( 3 / (3+7) ) => 100 * (3/10) => 30, 和 70。

于 2012-08-11T04:58:18.087 回答
0

Here's one way (taken from a progress bar plugin):

This is JavaScript, but the language is of course irrelevant.

var max = 250; // the total amount representing 100%
var current = $obj.val().length; // the length we are measuring

// important: current / max * 100

// use min() to ensure that the result isn't greater than 100 due to rounding
var ratio = Math.min( ( ( current / max ) * 100 ), 100 );

The key piece is dividing the current amount by the total amount, where the total amount (whatever it may be) represents 100%. That division operation should yield a value less than 1. To convert that to a 1-100 percentage, multiply by 100.

In my above example, if current = 125, and max = 250, then we have 125 / 250 = 0.5. Multiplying 0.5 * 100 gives 50. 125 is 50% of 250.

If you wanted to get both percentages, you could simply subtract the first result from 100.

Here is a complete working example of a HTML/CSS/jQuery progress bar for managing the maxlength of a textbox: http://jsfiddle.net/QfZPt/1/

于 2012-08-11T02:39:31.133 回答
0

如果您要求 100 中的数字百分比的物理表示,我将从获取百分比开始:

int number = 3; //or 7
int percent = number/100;

然后我会有一个 1 像素大的精灵并基于 缩放它percent,例如:

mybarsprite.scale = percent*100;

然后,您可以添加背景图像来创建条形图,并将其设为 100 像素。在同一位置添加两个精灵,较低 z 级别的背景精灵添加您有条形效果。

于 2012-08-11T02:43:55.417 回答