How to remove trailing decimals without rounding up? - javascript

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.

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

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

JQuery round up the length of a result

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

Getting a sum without rounding it off to two decimal places

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"

How do I round a number in JavaScript?

While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of
Name : Value
Name2 : Value2
etc.
The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form 2.20011E+17. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?
If you need to round to a certain number of digits use the following function
function roundNumber(number, digits) {
var multiple = Math.pow(10, digits);
var rndedNum = Math.round(number * multiple) / multiple;
return rndedNum;
}
You hav to convert your input into a number and then round them:
function toInteger(number){
return Math.round( // round to nearest integer
Number(number) // type cast your input
);
};
Or as a one liner:
function toInt(n){ return Math.round(Number(n)); };
Testing with different values:
toInteger(2.5); // 3
toInteger(1000); // 1000
toInteger("12345.12345"); // 12345
toInteger("2.20011E+17"); // 220011000000000000
According to the ECMAScript specification, numbers in JavaScript are represented only by the double-precision 64-bit format IEEE 754. Hence there is not really an integer type in JavaScript.
Regarding the rounding of these numbers, there are a number of ways you can achieve this. The Math object gives us three rounding methods wich we can use:
The Math.round() is most commonly used, it returns the value rounded to the nearest integer. Then there is the Math.floor() wich returns the largest integer less than or equal to a number. Lastly we have the Math.ceil() function that returns the smallest integer greater than or equal to a number.
There is also the toFixed() that returns a string representing the number using fixed-point notation.
Ps.: There is no 2nd argument in the Math.round() method. The toFixed() is not IE specific, its within the ECMAScript specification aswell
Here is a way to be able to use Math.round() with a second argument (number of decimals for rounding):
// 'improve' Math.round() to support a second argument
var _round = Math.round;
Math.round = function(number, decimals /* optional, default 0 */)
{
if (arguments.length == 1)
return _round(number);
var multiplier = Math.pow(10, decimals);
return _round(number * multiplier) / multiplier;
}
// examples
Math.round('123.4567', 2); // => 123.46
Math.round('123.4567'); // => 123
You can also use toFixed(x) or toPrecision(x) where x is the number of digits.
Both these methods are supported in all major browsers
You can use Math.round() for rounding numbers to the nearest integer.
Math.round(532.24) => 532
Also, you can use parseInt() and parseFloat() to cast a variable to a certain type, in this case integer and floating point.
A very good approximation for rounding:
function Rounding (number, precision){
var newNumber;
var sNumber = number.toString();
var increase = precision + sNumber.length - sNumber.indexOf('.') + 1;
if (number < 0)
newNumber = (number - 5 * Math.pow(10,-increase));
else
newNumber = (number + 5 * Math.pow(10,-increase));
var multiple = Math.pow(10,precision);
return Math.round(newNumber * multiple)/multiple;
}
Only in some cases when the length of the decimal part of the number is very long will it be incorrect.
Math.floor(19.5) = 19 should also work.

Categories