Getting a sum without rounding it off to two decimal places - javascript

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"

Related

When the result is round (1.10 1.30) does not display the 2nd decimal How do I do it?

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));

How to keep the zero's when parsing two strings to a float value

I'm trying to create a function that converts two strings to a float value.
Some external party created a theme with a backend where you should provide to values for a price:
priceBeforeComma
priceAfterComma
In the html this converts to:
<span>55,<sup>07</sup></span>
I need to do some calculations with the price as a float before splitting it up again for the html like you can see above.
I have a function that works pretty fine:
function parsePrice(price, priceDecimal) {
return parseFloat(price + "." + priceDecimal);
}
However, the problem I'm facing is that let's say I provide 07 as the decimal like above, the leading zero is removed, returning 55,7.
There is quite a big difference between 55,07 and 55,7. I expect to get back the zero as well like 55,07.
Any help will be much appreciated.
Your Code is right
function parsePrice(price, priceDecimal) {
return parseFloat(price + "." + priceDecimal);
}
parsePrice("55", "07");
if you send parsePrice("55","07") so you do not need to divide it by 100 because maybe you send it 007 then you should divide it by 1000. But your code will work properly if send string
Floats represent 07 as 07.0, so to get this to work correctly you'll need to write it as 0.07.
Here's what worked for me:
function parsePrice(price, priceDecimal) {
return parseFloat(price + priceDecimal);
}
var output = parsePrice(57, 0.07);
document.getElementById("test").innerHTML = output.toString().replace(".", ",");
<p id="test"></p>
This might be overkill, but you could use something that provides complete control over how numbers are converted to strings, and vice versa, for example: https://github.com/alexei/sprintf.js I have not used that library, but it promises to provide the same functionality as C printf, which would allow you to keep leading zeros. See the answer to the "C" language question here: Printing leading 0's in C?
(But, as an aside, also see my comment above - generally it's better to do financial calculations in integer arithmetic rather than floating point.)
So my suggestion would be to do this instead:
function price(dollars, cents) { // adjust for your currency
return parseInt(dollars)*100 + parseInt(cents);
}
function dollarsAndCents(price) {
let sign = "+";
if (price<0) {
sign = "-";
price = -price;
}
let cents = price % 100;
let dollars = (price-cents)/100;
dollars = dollars.toString();
cents = cents.toString();
if (cents.length<2) cents = "0" + cents;
return {sign: sign, dollars: dollars, cents: cents}
}
let price1 = price ("55", "07");
let price2 = price ("99", "99");
let total = price1 + price2;
console.log(dollarsAndCents(total))
//{ sign: '+', dollars: '155', cents: '06' }
let refund = -12345
console.log(dollarsAndCents(refund))
//{ sign: '-', dollars: '123', cents: '45' }
There you go, that's a pretty complete solution! Even handles negative amounts.
You should pass in Strings to your function instead by putting quotes around your numbers. Using numbers will always have the caveat of removing any leading zeroes.
function parsePrice(price, priceDecimal) {
return parseFloat(price + "." + priceDecimal);
}
parsePrice("55", "07");
Why not parse them separately as integers and add them together in the right proportions?
function parsePrice(price, priceDecimal) {
return parseInt(price) + (parseInt(priceDecimal) / 100);
}
console.log(parsePrice("55", "07"));

How to remove trailing decimals without rounding up?

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.

Rounding to two decimal places issue

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);

javascript division giving wrong answer? [duplicate]

This question already has answers here:
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 9 years ago.
alert(5.30/0.1);
This gives 52.99999999999999 but should be 53. Can anybody tell how and why?
I want to find that a number is divisible by a given number. Note that one of the number may be a float.
For the same reason that
0.1 * 0.2 //0.020000000000000004
Some decimal numbers can't be represented in IEEE 754, the mathematical representation used by JavaScript. If you want to perform arithmetic with these numbers in your question, it would be better to multiply them until they are whole numbers first, and then divide them.
Scale the numbers to become whole. Then modulus the result.
alert((5.30*10) % (0.1*10));
Now that you have read the article i commented, you should know the root of your problem.
You can partially work around that by scaling you floats...
Then just write a function which:
If its a float
Scale the Numbers
return a boolean representation of the divisibility of the number
function isDivisable(n, d) {
var ndI = 1 + "".indexOf.call(n, "."); //Index of the Number's Dot
var ddI = 1 + "".indexOf.call(d, "."); // Index of the Divisors Dot
if (ndI || ddI) { // IF its a float
var l = Math.max(("" + n).length - ndI, ("" + d).length - ddI); //Longest Decimal Part
var tmpN = (n * Math.pow(10, l)); //scale the float
var tmpD = (d * Math.pow(10, l));
return !~((tmpN % tmpD) - 1); //Substract one of the modulo result, apply a bitwise NOT and cast a boolean.
}
return !~((n % d) - 1); // If it isnt a decimal, return the result
}
console.log(isDivisable(5.30, 0.1));//true
Heres a JSBin
However...
As Integers are stored with 64bit precision, the maximum precision lies about (2^53),
and you will soon exceed the maximum precision when scaling larger numbers.
So it might be a good idea to get some sort of BigInteger Library for javascript
if you want to test floats for divisibility
To find if a number x is divisible by a number y you have to do x % y (modulo). If the result is 0, it is perfectly divisible, any other isn't.
You can get it by following:
var num = (5.30/0.1);
alert(num.toFixed(2));
this will give you 53.00.

Categories