got the following code:
var total = 0;
var $parent = $(this).closest('ul');
$parent.find('input:checked').each(function() {
total += parseInt($(this).val() * parseInt(115, 10) / parseInt(100, 10) / parseInt(36, 10));
});
$parent.find('span[class^=total]').html(Math.ceil(total));
The code checks the value of my inputs and with parseInt i convert them to another value (its a fixed price converted to monthly costs over 3 years).
This works but the value which i output in my html at the end wont get rounded up:
So my question is, how i can round up the value of my html output.
You're using parseInt() which will round down to the nearest int by default. If the original values are floating points you need to use parseFloat() instead.
$parent.find('input:checked').each(function() {
total += parseFloat($(this).val()) * 115 / 100 / 36;
});
Working example
Also note that you don't need to call parseInt() or parseFloat() on literal integer values.
Related
My program (which uses Math.round) does not display the second decimal when the result is round (ex: 1.10, 1.30) while yes when the result is not round (ex: 1.24, 2.47). How to change this?
function calcAmount2() {
var userAmount2 = document.getElementById("amount2").value;
if (userAmount2 = Number(amount2.value)) {
document.getElementById("marginAmount2").textContent =
Math.round(userAmount2 * 3) / 100 + "€";
}
}
(expected)1.10, 1.30 instead of (actually) 1.1 1.3
(Math.round(userAmount2 * 3) / 100).toFixed(2) + "€";
toFixed sets the number to always have 2 decimals.
I believe this is a duplicate of Format number to always show 2 decimal places
You want to use .toFixed(2) it seems, though be aware the result will be a String.
I am not sure how specific your answer has to be, but I would recommend you to use this instead:
const res = Number(Math.round(userAmount2 +'e2')+'e-2');
This is because toFixed has the rounding problem for some values such as 21.005.
Let me prove it to you over here:
console.log(Number(Math.round(20.005 +'e2')+'e-2'));
console.log(20.005.toFixed(2));
I can't get the numbers and text in same form field to force two decimal places or do Total figure.
This is the link.
I am trying to get the last 3 cells to work with two decimal places.
e.g. Total sq mt figure x Price should calculate the Cost cell.
Also want to get the Cost cell (NaN) working !
Thanks.
In general, you want to do something like this
function calc(val1, val2) { // this is NOT a replacement for your Calculate function
val1 = parseFloat(val1.replace(/[^\d\.-]/g, ''));
val2 = parseFloat(val2.replace(/[^\d\.-]/g, ''));
return (val1 * val2).toFixed(2);
}
NOTE: the above returns a STRING
and STOP redefining with Math.round in your code
var result = Math.round(num * 100.0) / 100.0;
Should format your number with two decimal places.
For example, I have a number 123.429. How can I remove the trailing decimals without rounding up to two decimal place.
Hence, I need the number to be up to two d.p. i.e 123.42.
Definitely toFixed() method or Math.round(num * 100) / 100 cannot be used in this situation.
The function you want is Math.floor(x) to remove decimals without rounding up (so floor(4.9) = 4).
var number = Math.floor(num * 100) / 100;
Edit: I want to update my answer because actually, this rounds down with negative numbers:
var Math.floor(-1.456 * 100) / 100;
-1.46
However, since Javascript 6, they have introduced the Math.trunc() function which truncates to an int without rounding, as expected. You can use it the same way as my proposed usage of Math.floor():
var number = Math.trunc(num * 100) / 100;
Alternatively, the parseInt() method proposed by awe works as well, although requires a string allocation.
var number = parseInt('' + (num * 100)) / 100;
You can convert it to a string and then simply truncate the string two places after the decimal, e.g.:
var s = String(123.429);
s.substring(0, s.indexOf('.') + 3); // "123.42"
Please note that there's no guarantee if you convert that final string back into a number that it'll be exactly representable to those two decimal places - computer floating point math doesn't work that way.
another v. cool solution is by using | operator
let num = 123.429 | 0
let num = 123.429 | 0
console.log(num);
let's get the variable name as "num"
var num = 123.429;
num=num*100;
num=num.toString();
num=num.split(".");
num=parseInt(num[0]);
num=num/100;
value of the num variable will be 12.42
Try this
number = parseFloat(number).toFixed(12);
number = number.substring(0, number.indexOf('.') + 3);
return parseFloat(number);
Not the fastest solution but the only one that handles an edge case like 0.0006*10000 = 5.999999999 properly, i.e. if you want to truncate to 4 decimal places and the value is exactly 0.0006, then using Math.trunc(0.0006 * (10 ** 4))/(10 ** 4) gives you 0.0005.
In Jquery, how do you take a variable and set a second variable with a decimal in front of the value of the first variable.
For example I have a variable that is set from a form input values. I named this variable subTotal. Now I want to take that variable and set another variable with a decimal in front of it so I can calculate a percentage by multiplying another input value.
So here is some of the code for example
var subTotal = self.calculateTotalFor(elems);
total += (quantity - 1) * NewVariable;
self.calculateTotalFor(elems); comes from the input on the form
NewVariable would be Subtotal with a decimal in front.
Try :
var subTotal = self.calculateTotalFor(elems), total = 0;
total += (quantity - 1) * NewVariable;
or
total += parseFloat((quantity - 1) * NewVariable);
Try this
var NewVariable = parseFloat("." + Subtotal);
This will take "." and your Subtotal value and perform a string
append
parseFloat will convert the string to a floating point number
I am using the following code snippet to calculate a total price. This works great except #totalPrice on some occasions expands out to for example $267.9999999999. How do I reformat #totalPrice within this function to just round to two decimals as is standard in dealing with price.
function getTotalCost(inventory) {
if(inventory) {
getTotalParts(inventory);
getTotalMarkup(inventory);
}
var labor = $('#labor').val() * 1;
var totals = 0;
for(i in totalMarkup) {
totals += totalMarkup[i];
}
totalCost = totals+labor;
/*if(totals == 0) {
totalCost = 0;
}*/
$('#totalPrice').html(totalCost);
}
You can have:
$('#totalPrice').html(totalCost.toFixed(2));
See:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed
Notice that toFixed method returns a formatted number, therefore converts the number to a string. It's not a problem here because html wants a string, but it's keep it in mind that in order to avoid concatenation of string when you expects sum of numbers. I believe you use $('#labor').val() * 1; for this very reason. However it's not necessary, it's better use method like parseFloat or the unary plus operator:
var labor = +$('#labor').val();
When working with javascript the floating points are always a bad. Best you can do is, round it up.
But in this case you can do
(totalCost).toFixed(2);
You can use Math.round function in JavaScript like this.
totalCost = Math.round(totalCost*100)/100;
$('#totalPrice').html(totalCost);