JQuery round up the length of a result - javascript

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

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

How to format numbers in javascript to two decimal digits?

I need to format numbers to two decimal digits in javascript. In order to do this I am using toFixed method which is working properly.
But in cases, where numbers don't have any decimal digits, it should not show decimal point
e.g. 10.00 should be 10 only and not 10.00.
.toFixed() converts the result to String,
so you need to convert it back to Number:
parseFloat( num.toFixed(2) )
or by simply using the Unary +
+num.toFixed(2)
both will give the following:
// 15.00 ---> 15
// 15.20 ---> 15.2
If you only want to get rid of the .00 case, than you can go for String manipulation using .replace()
num.toFixed(2).replace('.00', '');
Note: the above will convert your Number to String.
As an alternative to make this change global(if you need, of course), try this:
var num1 = 10.1;
var num2 = 10;
var tofixed = Number.prototype.toFixed;
Number.prototype.toFixed = function(precision)
{
var num = this.valueOf();
if (num % 1 === 0)
{
num = Number(num + ".0");
}
return tofixed.call(num, precision);
}
console.log(num1.toFixed(2));
console.log(num2.toFixed(2));
Fiddle. This is a mix of this and this post.

Javascript Number Formatting

Certainly a stupid question, please forgive me. My customer wants decimal numbers to display with five digits. For example: 100.34 or 37.459. I was accomplishing this with val.toPrecision (5);; however, when my numbers get really small, I stop getting what I want. For example, if my number is 0.000347, it displays 0.00034700. Now, I understand why it's doing this, but what I don't know is how to get it to display 0.0003. Any thoughts?
Math.round(0.000347 * 1e4) / 1e4
Or with toFixed:
Number.prototype.toNDigits = function (n) {
return (Math.abs(this) < 1) ?
this.toFixed(n - 1) :
this.toPrecision(n);
};
http://jsfiddle.net/HeQtH/6/
Our problem is with numbers less than 1 obviously. So catch them and deal them separately
function SetPrecisionToFive(n){
return (n > 1) ? n.toPrecision (5) : (Math.round(n * 1e4) / 1e4).toString();
}
You can use the toFixed method to accomplish this. For example: (0.000347).toFixed(4)
The Javascript toFixed() function will truncate small numbers to a fixed decimal precision, eg:
var num = .0000350;
var result = num.toFixed(5); // result will equal .00003

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