My script dynamically produces a number and this can range from anything between 1-278.
I then need to do a number is what percent of 603.
Say for example that number turns out to be 67, i then need to know what percent 67 is of 603.
The function should return 11.1..%
Basically the second option on this page:
http://www.percentagecalculator.net/
Can i do this with javascript?
var total = 603;
var num = 67 // what have been created dynamically beforehand
num is what percent of total?
Well, you just do :
percentage = (num/total)*100;
Here you go:
var total = 603;
var num = 67 /*whatever was generated before*/;
var percentage = num / total * 100;
here is a jsfiddle to demonstrate my solution: http://jsfiddle.net/zfhkB/2/
Hope I helped :)
Related
Was using ExtJS for formatting numbers to percentage earlier. Now as we are not using ExtJS anymore same has to be accomplished using normal JavaScript.
Need a method that will take number and format (usually in %) and convert that number to that format.
0 -> 0.00% = 0.00%
25 -> 0.00% = 25.00%
50 -> 0.00% = 50.00%
150 -> 0.00% = 150.00%
You can use Number.toLocaleString():
var num=25;
var s = Number(num/100).toLocaleString(undefined,{style: 'percent', minimumFractionDigits:2});
console.log(s);
No '%' sign needed, output is:
25.00%
See documentation for toLocaleString() for more options for the format object parameter.
Here is what you need.
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)+"%");
Modern JS:
For any of these, remove * 100 if you start with a whole number instead of decimal.
Basic
const displayPercent = (percent) => `${(percent * 100).toFixed(2)}%`;
Dynamic with safe handling for undefined values
const displayPercent = (percent, fallback, digits = 2) =>
(percent === null || percent === undefined) ? fallback : `${(percent * 100).toFixed(digits)}%`;
Typescript:
const displayPercent = (percent: number) => `${(percent * 100).toFixed(2)}%`;
<!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>
I had decimal values such as 0.01235 and 0.016858542 that I wanted to convert to percentages 1.235% and 1.6858542% respectively. I thought it was going to be easy, just calculate (0.012858542 * 100) and I'm good to go. I was wrong, (0.012858542 * 100) = 1.2858542000000002 because of decimal conversion.
Let's add toFixed() to the calculation and I end up with the right value.
(0.012858542*100).toFixed(7) // returns "1.2858542"
(0.01235*100).toFixed(7) // returns "1.2350000"
I don't like to show four trailing zeros when they're unnecessary. One solution I thought about was to use replace() to remove all trailing zeros but I ended up using Numeral.js instead because it does all the work for me while it's lightweight. I can recommend it!
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"
Transform number to percentage with X float decimal positions
function toPercent(number, float) {
var percent = parseFloat(number * 100).toFixed(float) + "%";
return percent;
}
I am in need of some help.
I have a stupidly complex piece of math that I need to turn into a javascript equation and it's not working (annoyingly!!).
Basically the sum is:
No#1 / No#2 = Result1
Result1 - 1 = Result2
Result2 * 100 = Result3
Result3 rounds up or down - display result.
I hope that makes sense.
The code I am using is:
var rc1TyreRatio2 = Number(Apperyio("rc1TyreRatio2").val());
var rc1Test1 = Number(Apperyio("rc1Test1").val());
var rc1Test2 = Number(Apperyio("rc1Test2").val());
var rc1Test1 = rc1InterAxle / rc1TyreRatio2;
var rc1Test2 = rc1Test - 1;
var rc1Lead = rc2Test * 100;
Apperyio('rc1Lead').val(rc1Lead.toFixed(2) + "%");
The components are standing JQuery Mobile 'textareas' & they are: rc1TyreRatio2 | rc1Test1 | rc1Test2 | rc1Lead.
I know it's in the appery.io platform, it wasn't my first choice, but my client's as they have other stuff hosted there, so I have to work with it, it use's JQM JavaScript just fine,
Any idea's how I can get this working? using just JavaScript and no HTML at all.
Thank you all,
- Tech-Xcellent
Use brackets to do certain calculations that are unique to get a result. You can chain as many brackets with calculations as you want.
i.e
(calculation A = result) * (calculation B = result) / (calculation C = result) + (calculation D = result)
Example
var noa = 20;
var nob = 10;
var Total = (noa / nob - 1) * 100;
alert (Math.round(Total))
Result is 100
if i dint use brackets e.g var Total = noa / nob - 1 * 100; the result would show -98 which is wrong
Demo
I have two vars that I need to subtract from one another.
My code is
var discountedTotal = totalAmount - discountAmount;
totalAmount is static and that value is 3,916.64
discountAmount is entered via an input and is a round number i.e. 500
so discountedTotal = 3,916.64 - 500;
I am getting a result of NAN, what is the best way to handle this scenario? Thanks
var totalAmount = '3,916.64';
var discountAmount = 500;
totalAmount = parseFloat(totalAmount.replace(',',''));
console.log(totalAmount);
discountedTotal = totalAmount - discountAmount;
console.log(discountedTotal);
Try this. Hope it helps.
How can I add percent to a sum? I have tried var sum = 3.25 + '3.4%'; but it didn't work. I'm just getting 0.00 as an answer.
To "add a percent to a number" means "multiply the number by (1 + pct)":
var sum = 3.25;
sum = sum * (1 + 0.034);
You could equivalently skip the 1 (that's just the way I think about it) and add:
var sum = 3.25;
sum += sum * 0.034;
So if you're starting off with a string representation of a percentage, you can use parseFloat() to make it a number:
var pct = "3.4%"; // or from an <input> field or whatever
pct = parseFloat(pct) / 100;
The parseFloat() function conveniently ignores trailing non-numeric stuff like the "%" sign. Usually that's kind-of a problem, but in this case it saves the step of sanitizing the string.
The simplest method is to use arithmetic operators.
var sum = 3.25
sum += sum *= 0.034;
< 3.3605
String concatenation and number adding using the same + symbol. You need to use () around the numbers.
var sum = (3.25+3.4)+"%";
let's assume that you want to add x percent to the current number :
const percentage = 14.5; let number = 100 const numberPlusPercentage = number + number / 100 * percentage
console.log('result = 'numberPlusPercentage.toFixed(2))
result = 114.5
I've got a simple table that allows users to enter 2 numbers, and then a script then calculates the annual average and gets the totals for all rows that have the same option in the select menu.
I've setup a sample JSFiddle:
http://jsfiddle.net/fmdataweb/73Jzc/1/
that shows how this works. I've just noticed that at times I get a strange rounding error (I want it to round to one decimal place). For example if you select "moderate" and then enter 5 and 4 for an average of 0.4, then click the button to create a new row and select "moderate" again then enter 3 and 40 for an average of 2.3 you'll notice the total for the moderate is "2.6999999999999997" when it should be 2.7.
If you enter other numbers it's fine so far in my testing but for some reason these combinations don't get rounded for the totals and I'm not sure why. Appreciate if anyone can point out the error in my script. Here's the script that does the averages and totals:
$('#nextYear')
.on('change', 'select', calc)
.on('keyup', 'input', calc);
function calc(){
$('#nextYear tr:has(.risk)').each(function(i,v){
var $cel = $(v.cells);
var $risk = $cel.eq(1).find('option:selected').val();
var $numb = $cel.eq(2).find('input').val();
var $weeks = $cel.eq(3).find('input').val();
var $avg = ($numb * $weeks) / 52;
var $avgRounded = Math.round( $avg * 10 ) / 10;
$cel.eq(4).find('input').val($avgRounded);
});
var tot = {};
$('#nextYear tr:has(.risk) option:selected')
.map(function(i){
var el = $(this).val();
var qty = parseFloat($('#nextYear tr:has(.risk)').eq(i).find('td:last').prev().find('input').val());
if (!tot.hasOwnProperty(el)) {
tot[el] = 0;
}
tot[el] += qty
return tot;
}).get();
// console.log(tot);
$('#textfield6').val(tot.moderate);
$('#textfield7').val( tot.high );
}
You problem is here:
$('#textfield6').val(tot.moderate);
$('#textfield7').val( tot.high );
You must round them like you did with
var $avgRounded = Math.round( $avg * 10 ) / 10;
or using .toFixed(1)
Edit:
Then, the code is:
$('#textfield6').val(tot.moderate.toFixed(1));
$('#textfield7').val(tot.high.toFixed(1));
You can see it here: http://jsfiddle.net/73Jzc/2/
Try $avg.toFixed(1); instead of Math.round( $avg * 10 ) / 10;