I am loading numeric values to 2 decimal places using Javascript. All values seem okay, apart from £299.90 and £499.90, which loads as £299.9 and £499.9
Current code:
//ROUNDING FUNCTION
function round(num, decimals) {
return Math.round(num * Math.pow(10, decimals)) / Math.pow(10, decimals);
}
//LOADING VALUES - Line cost variable is £49.99/£29.99 * 10
jQuery(".content").html("£" + round(lineCost, 2));
What I have tried:
jQuery(".content").html(parseFloat(lineCost * 100) / 100).toFixed(2);
jQuery(".content").html(Number(lineCost).toFixed(2));
Any ideas?
Thanks.
You can try with toFixed method on a float/integer value:
var value = 0.127456;
value.toFixed(2);
Output:
0.13
In your case:
jQuery(".content").html("£" + lineCost.toFixed(2));
If lineCost is a string, parse it to float:
jQuery(".content").html("£" + parseFloat(lineCost).toFixed(2));
You are over complicating it.
It just requires
parseFloat(lineCost).toFixed(2);
Here is a demo fiddle.
Actually rounding means to convert a number like 10.5 to 11 or 12.49 to 12 so you should not round the number if you want to use a float with decimals, instead you should just use something like this:
var lineCost = 12.5;
parseFloat(lineCost).toFixed(2);
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));
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.
I am using this code:
$("#total_percentage").text(
(parseInt($("#capacity").text(), 10) / parseInt($("#total").text(), 10))
);
My problem is that #total_percentage sometimes gives a long result.
e.g: 2.33333333333
Is there a way to setting it so it rounds up / shows only max of 2 digits?
for example: 2 or 10
To round up use the Javascript Math library.
$("#total_percentage").text(
(Math.ceil(parseInt($("#capacity").text(), 10) / parseInt($("#total").text(), 10)))
);
You can use toFixed():
$("#total_percentage").text(
(parseInt($("#capacity").text(), 10) / parseInt($("#total").text(), 10)).toFixed(2)
);
References:
toFixed().
If you want to display two digits to the right of the decimal, Math.toFixed is the solution:
(2.33333333).toFixed(2) === "2.33"
Note that this results in a string, not a number. If you want to display 2 digits total, Math.toPrecision is what you want:
(2.33333333).toPrecision(2) === "2.3"
Again, this results in a string. To get back to a number (if desired), you can use parseFloat.
A final note that both these functions will also round your number. For example:
(1.23456).toPrecision(4) === "1.235"
If you want to truncate your number without rounding, you can write a function like this:
function truncate(num,precision) {
var muldiv = Math.pow(10,precision-1);
return Math.floor(num * muldiv) / muldiv;
}
truncate(1.23456,4) === 1.234
Here is a jsFiddle demonstrating each method:
---jsFiddle DEMO---
Forgive me if I'm too noob about this. Recently, I post a question regarding the rounding off two decimal places. Now, How can I get the sum of these numbers but I only need the two decimals w/out rounding it off. This is javascript im working.
Example: 12.876 + 36.278 = 49.154. I need this answer to be... 49.15 only. Or
another one: 12.876 + 1 = 13.876. I need this answer to be... 13.87
Here is my code (with round off to two decimal places)
function civ(){
civ1=Number(document.addition.scc.value);
civ2=Number(document.addition.ccc.value);
civ3=Number(document.addition.ncc.value);
civ4=Number(document.addition.vch.value);
civ5=Number(document.addition.mch.value);
civ6=Number(document.addition.nlch.value);
civ7=Number(document.addition.slch.value);
valNum1=Math.round((civ1+civ2+civ3+civ4+civ5+civ6+civ7)*10)/10;
document.addition.civ123.value=valNum1;
}
Super thanks to those who are helping me everyday! :)
Math.floor(N * 100) / 100
Will strip off past two decimal places; Math.floor() is essentially Round Down no matter what.
Math.floor(N * 100) / 100 may not work always.
For Example,
4.56 becomes 4.55
If myNumber is the number you want to have two decimals...
myNumber.toFixed(2)
should work. Source: http://www.w3schools.com/jsref/jsref_tofixed.asp
A very old question, but I saw it didn't have an acceptable answer. As #user3006769 mentioned, some numbers don't work if you use Math.floor(N*100)/100.
Another approach is to count how many digits there are before the decimal, then convert your number to a string, chop off any characters to the right of the 2nd decimal, then convert it back to a number:
function roundDownDecimals(num, decimals) {
const preDecimalDigits = Math.floor(num).toFixed(0).length;
return parseFloat(num.toFixed(decimals + 1).slice(0, preDecimalDigits + decimals + 1));
}
roundDownDecimals(4.56, 2);
// returns 4.56
roundDownDecimals(13.876, 2);
// returns 13.87
roundDownDecimals(4.10, 2);
// returns 4.1
If you need to preserve trailing 0's, leave off the parseFloat.
function roundDownDecimals(num, decimals) {
const preDecimalDigits = Math.floor(num).toFixed(0).length;
return num.toFixed(decimals + 1).slice(0, preDecimalDigits + decimals + 1);
}
roundDownDecimals(4.10, 2);
// returns "4.10"
In php, we have number_format(). Passing it a value such as:
number_format(3.00 * 0.175, 2);
returns 0.53, which is what I would expect.
However, in JavaScript using toFixed()
var num = 3.00 * 0.175;
num.toFixed(2);
returns 0.52.
Ok, so perhaps toFixed is not what I want... Maybe something like this...
var num = 3.17 * 0.175;
var dec = 2;
Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
No, that doesn't work either. It will return 0.56.
How can I get a number_format function in JavaScript that doesn't give an incorrect answer?
Actually I did find an implementation of number_format for js, http://phpjs.org/functions/number_format, but it suffers from the same problem.
What is going on here with JavaScript rounding up? What am I missing?
JavaScript does badly with floating point numbers (as do many other languages).
When I run
3.000 * 0.175
In my browser, I get
0.5249999999999999
Which will not round up to 0.525 with Math.round. To circumvent this, you kind of have to multiply both sides until you get them to be integers (relatively easy, knowing some tricks help though).
So to do this we can say something like this:
function money_multiply (a, b) {
var log_10 = function (c) { return Math.log(c) / Math.log(10); },
ten_e = function (d) { return Math.pow(10, d); },
pow_10 = -Math.floor(Math.min(log_10(a), log_10(b))) + 1;
return ((a * ten_e(pow_10)) * (b * ten_e(pow_10))) / ten_e(pow_10 * 2);
}
This may look kind of funky, but here's some pseudo-code:
get the lowest power of 10 of the arguments (with log(base 10))
add 1 to make positive powers of ten (covert to integers)
multiply
divide by conversion factor (to get original quantities)
Hope this is what you are looking for. Here's a sample run:
3.000 * 0.175
0.5249999999999999
money_multiply(3.000, 0.175);
0.525
The toFixed function is working correctly. It truncates past the specified amount of fraction digits.
Why all the powers?? Why not just add slightly less than 1/2 a cent and round:
(3.00 * 0.175 + 0.0049).toFixed(2)
Never had any accountants complain about the output.
I think the problem you are encountering is with floating point math as opposed to the rounding itself.
Using the firebug console for testing, logging the result of 3.00 * 0.175 given 0.524999.... So rounding this number down is actually correct.
I don't know if there is a good solution to your problem, but in my experience when working with currency: it is easier to work in the smallest unit (cents) and then convert for display.
Why didn't you just use Math.round( num * Math.pow( 10, dec ) ) / Math.pow( 10, dec) )?
EDIT: I see, the problem is that 3 * 0.175 gives you 0.52499999999999991, leading you to want an additional rounding step. Maybe just adding a small amount would work:
Math.round( num * Math.pow( 10, dec ) + 0.000000001 ) / Math.pow( 10, dec) )
I know this is old but this is how I usually solve a rounding problem. This can be put in a function easily but for now I just put in simple vars for right now. If this doesn't work you could use money_format() or number_format() as a start from php.js (more info below).
var n = (3.00 * 0.175);
n = Math.round(n * Math.pow(10, 3)) / Math.pow(10, 3);
Math.round(n*100)/100;
comes out to 0.53 (0.5249999999999999)
var n = (3.00 * 0.175);
n = Math.round(n * Math.pow(10, 3)) / Math.pow(10, 3);
Math.round(n*100)/100;
comes out to 0.56 (0.55475)
It also looks like the php.js repo is being kept up on GitHub https://github.com/kvz/phpjs so if there isn't a function that is not performing correctly an issue can be submitted.
Anyway figured this information may help someone looking later on.