Calculate percentage Javascript
It seems working :
HTML :
<input type='text' id="pointspossible"/>
<input type='text' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>
JavaScript :
$(function(){
$('#pointspossible').on('input', function() {
calculate();
});
$('#pointsgiven').on('input', function() {
calculate();
});
function calculate(){
var pPos = parseInt($('#pointspossible').val());
var pEarned = parseInt($('#pointsgiven').val());
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = ((pEarned/pPos) * 100).toFixed(3);
}
$('#pointsperc').val(perc);
}
});
Demo : http://jsfiddle.net/vikashvverma/1khs8sj7/1/
How to calculate percentage with simple JavaScript code
Use oninput
as I did below. Also give the amount input field a name. it's missing in the OP.
// Percentage Calculator const myForm = document.getElementById('my-form');
myForm.oninput = () => { myForm.result.value = percentageCalculator(myForm.amount.value, myForm.percent.value);}
function percentageCalculator(amount, percent) { return ((percent * amount) / 100).toFixed(2)}
fieldset { margin-top: 1em;} label { display: inline-block; width: 8em; text-align: left; } input { font-size: .8em; text-align: left; display: inline-block; width: 8em; } output::before { content: ''; } output { font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right; }
<h2>Percentage Calculator</h2>
<form action="" id="my-form"> <fieldset> <legend>Calculate Percentage :</legend> <append>What is <input type="number" name="percent" step=any min=0> % of </append> <label><input type="number" name="amount" class="amount" step=any min=0></label> </fieldset> <fieldset><br> <legend>Result :</legend> <output name="result" value='0'></output>
<br> <button type="reset">Reset Calculator!</button> </fieldset></form>
How to calculate percentage in JavaScript
See what is changing the values of hits and misses field.
Whenever there is a change in any of those fields, do percentage = (hits/(hits+misses)) *100
to get the percentage. (I see you are doing (misses/hits)*100
in your example)
Also, take care in rounding off the percentage using percentage.toFixed(2)
or Math.round(percentage)
as mentioned by Chris in another answer and add the %
sign after it or in the name of the field.
Hope it helps.
Get accurate percentage calculation in JavaScript
You are using floats to perform calculations. Due to their internal representation, there can be precision issues, such as the one you are facing. See the link for more details.
In summary, as you seem to be handling currency calculations, your best option is to use, instead of float, a specific datatype such as currency.js:
const m = (amount) => currency(amount, { precision: 10 })
const getAmount = (amount, rate) => {
const fee = m(amount).multiply(m(rate).divide(100));
const amountAfterFee = m(amount).subtract(fee);
const calculatedRate = m(1).subtract(amountAfterFee.divide(amount)).multiply(100);
return { amount, fee, amountAfterFee, rate, calculatedRate };
};
console.log(getAmount(3000, "5"));
// { amount: 3000, fee: 150, amountAfterFee: 2850, rate: 5, calculatedRate: 5.000000000000004 }
console.log(getAmount(3000, "6.0"));
// { amount: 3000, fee: 180, amountAfterFee: 2820, rate: 6, calculatedRate: 6.000000000000005 }
console.log(getAmount(3000, "7.3"));
// { amount: 3000, fee: 219, amountAfterFee: 2781, rate: 7.3, calculatedRate: 7.299999999999995 }
console.log(getAmount(3000, "8.12345"));
// { amount: 3000, fee: 243.7035, amountAfterFee: 2756.2965, rate: 8.12345, calculatedRate: 8.123449999999998 }
<script src="https://cdn.jsdelivr.net/npm/currency.js"></script>
Calculate the percentage for a Value when button is clicked using JS PHP
The solution is little complex, but its just coding:
i suggest you to change the value of name for radios button s for each row, or you could just select only one radio button among all, so i suppose you want to select the choice for each row. so i have rename radios1 for the second row
//select the radio for 30%
$("#radio1, #radio7").prop("checked", true);
let percent90days = 60.0;
let percent60days = 30.0;
//save initial values
$(".table-row div[data-label=Percent]").each( function(){
let valuetosave = $(this).text().replace("%","");
$(this).attr("data-save", valuetosave)
});
//trap event click on radio
$(".table-row input[type=radio]").on("click", function(){
let idRadio = $(this).attr("id")
let percentAsked = $(this).closest(".table-row").find(`label[for=${idRadio}]`).text();
let selectorToTrapValue = $(this).closest(".table-row").find("div[data-label=Percent]");
let initialvalue = parseFloat(selectorToTrapValue.data("save"));
//i dunno what you want for your calculus its not clear
// i dunno if you want to add 30% or you want increase the initial value of 30%
// so i display value
console.log("initial value: " + initialvalue + " percentAsked: " + percentAsked)
//if percentAsked is 30% display the initialvalue
if(percentAsked == "30"){
selectorToTrapValue.text(initialvalue + "%")
return;
}
//calculate the new value
if(percentAsked == "60"){
selectorToTrapValue.text(initialvalue + initialvalue * percent60days / 100.0 + "%")
}else if (percentAsked == "90"){
selectorToTrapValue.text(initialvalue + initialvalue * percent90days / 100.0 + "%")
}
});
.radio-toolbar input[type="radio"] {
display: none;
}
.radio-toolbar label {
display: inline-block;
border: 1px solid #ffc107;
padding: 4px 11px;
font-family: Arial;
font-size: 16px;
cursor: pointer;
border-radius: 0.2rem;
}
.radio-toolbar input[type="radio"]:checked+label {
background-color: #ffc107;
}
.headernew {
text-align: center;
}
.container {
max-width: 1000px;
margin-left: auto;
margin-right: auto;
padding-left: 10px;
padding-right: 10px;
}
h2 {
font-size: 26px;
margin: 20px 0;
text-align: center;
}
h2 small {
font-size: 0.5em;
}
.responsive-table li {
border-radius: 3px;
padding: 25px 30px;
display: flex;
justify-content: space-between;
margin-bottom: 15px;
}
.responsive-table .table-header {
background-color: #95A5A6;
font-size: 12px;
letter-spacing: 0.03em;
}
.responsive-table .table-row {
background-color: #ffffff;
box-shadow: 0px 0px 9px 0px rgba(0, 0, 0, 0.1);
}
.responsive-table .col-1 {
flex-basis: 10%;
font-size: 14px;
display: flex;
align-items:center;
margin-left: -40px;
margin-right: 32px;
}
.responsive-table .col-2 {
flex-basis: 40%;
font-size: 14px;
display: flex;
align-items:center;
margin-right: 30px;
}
.responsive-table .col-3 {
flex-basis: 25%;
font-size: 14px;
display: flex;
align-items:center;
}
.responsive-table .col-4 {
flex-basis: 25%;
font-size: 14px;
display: flex;
align-items:center;
}
@media all and (max-width: 356px) {
.responsive-table .table-header {
display: none;
}
.responsive-table li {
display: block;
}
.responsive-table .col {
flex-basis: 100%;
}
.responsive-table .col {
display: flex;
padding: 10px 0;
}
.responsive-table .col:before {
color: #6C7A89;
padding-right: 10px;
content: attr(data-label);
flex-basis: 50%;
text-align: right;
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head><link rel="stylesheet" href="https://coinscord.com/coin/bootstrap/css/bootstrap.min.css"></head>
<ul class="responsive-table">
<li class="table-header">
<div class="col col-1">Token</div>
<div class="col col-2">Est. APY</div>
<div class="col col-3">Duration (days)</div>
<div class="col col-4"></div>
</li>
<li class="table-row">
<div class="col col-1" data-label="icon"><img src="" alt="icon" style="width:30px;height:30px;"> ADA</div>
<div class="col col-2" data-label="Percent"><font color="green">
15%</font></div>
<div class="col col-3" data-label="Days"><div class="radio-toolbar">
<input type="radio" id="radio1" name="radios" value="all">
<label for="radio1">30</label>
<input type="radio" id="radio2" name="radios" value="false">
<label for="radio2">60</label>
</div></div>
</li>
<li class="table-row">
<div class="col col-1" data-label="icon"><img src="../coin/images/coins/bnb.png" alt="bnb" style="width:30px;height:30px;"> BNB</div>
<div class="col col-2" data-label="Percent"><font color="green">
10.4%</font></div>
<div class="col col-3" data-label="Days"><div class="radio-toolbar">
<input type="radio" id="radio7" name="radios1" value="all" >
<label for="radio7">30</label>
<input type="radio" id="radio72" name="radios1" value="false" >
<label for="radio72">60</label>
</div></div>
</li>
</ul>
JavaScript - Calculating the percentage of each index in array
You cannot perform this in the same loop. You need to use separate loop after you have the total sum.
let dataArr = [10232, 23212, 98321, 32909, 29121, 20123]
let dataSum = 0
for (let i = 0; i < dataArr.length; i++) { dataSum += dataArr[i]}
const finalSum = dataArr.map(item => item * 100 / dataSum);console.log(dataSum, "dataSum")console.log(finalSum, "finaaaal")
Calculate the percentage of an object property
const data = [{
"date": "26/08/2021",
"walking": 965.2107,
"running": 964.0539,
"sleeping": 962.1473,
"swimming": 961.8081,
"studying": 961.5081,
}];
const dataInPerCents = data.map(item => {
const itemCopy = {...item};
const keys = Object.keys(itemCopy).filter(key => key !== "date");
const sum = keys.reduce((sum, key) => sum + itemCopy[key], 0);
keys.forEach(key => itemCopy[key] = Math.round(100 * itemCopy[key] / sum));
itemCopy.top3 = keys.sort((key1, key2) => item[key2] - item[key1]).slice(0, 3); // Asked in comment below
return itemCopy;
});
console.log(dataInPerCents);
Related Topics
Show Only a Limited Number of Rows in a Table
Typescript Property Does Not Exist on Type {}
Size of Json Object (In Kbs/Mbs)
How to Get 30 Days Prior to Current Date
How to Create a Remember Me Function in Login Without Using Form in JavaScript or Jquery
Uploading Multiple Files Using Formdata()
Javascript Innerhtml Not Updating Element
Detecting When User Scrolls to Bottom of Div With React Js
How to Wait Until All JavaScript Files Are Loaded Before Executing JavaScript Code
How to Refresh the Data in a Jqgrid
Angular:How to Implement Condtion Based Click Event
How to Wait for Element to Disappear in Cypress
How to Combine First Name and Last Name in JavaScript
Move an Image With JavaScript Using Mouse Events
How to Combine Object Values from Separate Lines into One Line
Push Objects into an Array in Reactjs
How to Get the Difference Between Two Arrays of Objects in JavaScript