How do I round a number in JavaScript? - 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.

Related

PHP round($num,2) and javascript toFixed(2) is not giving right output for this value 53.955

I have one php function and having
phpans = round(53.955,2)
and javascript function
var num = 53.955;
var jsans = num.toFixed(2);
console.log(jsans);
both jsans and phpans is giving different $phpans = 53.96 ans jsans = 53.95 . I can not understand why this is happening ..
Thanks is Advance
Because computers can't represent floating numbers properly. It's probably 53.95400000000009 or something like that. The way to deal with this is multiply by 100, round, then divide by 100 so the computer is only dealing with whole numbers.
var start = 53.955,
res1,
res2;
res1 = start.toFixed(2);
res2 = (start * 100).toFixed(0) / 100;
console.log(res1, res2);
//Outputs
"53.95"
53.96
JAvascript toFixed:
The toFixed() method converts a number into a string, keeping a specified number of decimals.
php round:
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
Conclusion tofixed not working like php round. precision Specifies the number of decimal digits to round to.
Javascript function :
function round_up (val, precision) {
power = Math.pow (10, precision);
poweredVal = Math.ceil (val * power);
result = poweredVal / power;
return result;
}

parseInt not converting decimal to binary?

From my understanding the binary number system uses as set of two numbers, 0's and 1's to perform calculations.
Why does:
console.log(parseInt("11", 2)); return 3 and not 00001011?
http://www.binaryhexconverter.com/decimal-to-binary-converter
Use toString() instead of parseInt:
11..toString(2)
var str = "11";
var bin = (+str).toString(2);
console.log(bin)
According JavaScript's Documentation:
The following examples all return NaN:
parseInt("546", 2); // Digits are not valid for binary representations
parseInt(number, base) returns decimal value of a number presented by number parameter in base base.
And 11 is binary equivalent of 3 in decimal number system.
var a = {};
window.addEventListener('input', function(e){
a[e.target.name] = e.target.value;
console.clear();
console.log( parseInt(a.number, a.base) );
}, false);
<input name='number' placeholder='number' value='1010'>
<input name='base' placeholder='base' size=3 value='2'>
As stated in the documentation for parseInt: The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
So, it is doing exactly what it should do: converting a binary value of 11 to an integer value of 3.
If you are trying to convert an integer value of 11 to a binary value than you need to use the Number.toString method:
console.log(11..toString(2)); // 1011
.toString(2) works when applied to a Number type.
255.toString(2) // syntax error
"255".toString(2); // 255
var n=255;
n.toString(2); // 11111111
// or in short
Number(255).toString(2) // 11111111
// or use two dots so that the compiler does
// mistake with the decimal place as in 250.x
255..toString(2) // 11111111
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
So you are telling the system you want to convert 11 as binary to an decimal.
Specifically to the website you are referring, if you look closer it is actually using JS to issue a HTTP GET to convert it on web server side. Something like following:
http://www.binaryhexconverter.com/hesapla.php?fonksiyon=dec2bin&deger=11&pad=false
The shortes method I've found for converting a decimal string into a binary is:
const input = "54654";
const output = (input*1).toString(2);
print(output);
I think you should understand the math behind decimal to binary conversion. Here is the simple implementation in javascript.
main();
function main() {
let input = 12;
let result = decimalToBinary(input);
console.log(result);
}
function decimalToBinary(input) {
let base = 2;
let inputNumber = input;
let quotient = 0;
let remainderArray = [];
let resultArray = [];
if (inputNumber) {
while (inputNumber) {
quotient = parseInt(inputNumber / base);
remainderArray.push(inputNumber % base);
inputNumber = quotient;
}
for (let i = remainderArray.length - 1; i >= 0; i--) {
resultArray.push(remainderArray[i]);
}
return parseInt(resultArray.join(''));
} else {
return `${input} is not a valid input`;
}
}
This is an old question, however I have another solution that might contribute a little bit. I usually use this function to convert a decimal number into a binary:
function dec2bin(dec) {
return (dec >>> 0).toString(2);
}
The dec >>> 0 converts the number into a byte and then toString(radix) function is called to return a binary string. It is simple and clean.
Note: a radix is used for representing a numeric value. Must be an integer between 2 and 36. For example:
2 - The number will show as a binary value
8 - The number will show as an octal value
16 - The number will show as an hexadecimal value
function num(n){
return Number(n.toString(2));
}
console.log(num(5));
This worked for me: parseInt(Number, original_base).toString(final_base)
Eg: parseInt(32, 10).toString(2) for decimal to binary conversion.
Source: https://www.w3resource.com/javascript-exercises/javascript-math-exercise-3.php
Here is a concise recursive version of a manual decimal to binary algorithm:
Divide decimal number in half and aggregate remainder per operation until value==0 and print concatenated binary string
Example using 25: 25/2 = 12(r1)/2 = 6(r0)/2 = 3(r0)/2 = 1(r1)/2 = 0(r1) => 10011 => reverse => 11001
function convertDecToBin(input){
return Array.from(recursiveImpl(input)).reverse().join(""); //convert string to array to use prototype reverse method as bits read right to left
function recursiveImpl(quotient){
const nextQuotient = Math.floor(quotient / 2); //divide subsequent quotient by 2 and take lower limit integer (if fractional)
const remainder = ""+quotient % 2; //use modulus for remainder and convert to string
return nextQuotient===0?remainder:remainder + recursiveImpl(nextQuotient); //if next quotient is evaluated to 0 then return the base case remainder else the remainder concatenated to value of next recursive call
}
}
To get better understanding, I think you should try to do the math of that conversion by yourself.
(1) 11 / 2 = 5
(1) 5 / 2 = 2
(0) 2 / 2 = 1
(1) 1 / 2 = 0
I made a function based on that logic
function decimalToBinary(inputNum) {
let binary = [];
while (inputNum > 0) {
if (inputNum % 2 === 1) {
binary.splice(0,0,1);
inputNum = (inputNum - 1) / 2;
} else {
binary.splice(0,0,0);
inputNum /= 2;
}
}
binary = binary.join('');
console.log(binary);
}
This is what I did to get the solution:
function addBinary(a,b) {
// function that converts decimal to binary
function dec2bin(dec) {
return (dec >>> 0).toString(2);
}
var sum = a+b; // add the two numbers together
return sum.toString(2); //converts sum to binary
}
addBinary(2, 3);
I first converted the decimal number to binary like it said, and I got the function from w3schools under the JavaScript Bitwise lesson. Then to make it easier on myself, I created the variable "sum" which does the addition and finally, I made the addBinary function return the sum as a binary code, then called it. It passed in CodeWars. I hope this makes sense and it helps you.
Just use Number(x).toString(base). Where base needs to be equals 2.
var num1=13;
Number(num1).toString(2)
result: "1101"
Number(11).toString(2)
result: "1011"
It seems like the conversion with the string radix (dec >>> 0).toString(2) is returning the binary number formatted in the wrong direction. I have validated this solution in Chrome. In case anyone wants to manually calculate binary for validation, from left to right you add the numbers together that correspond to a 1 position in your binary number mapping to [1][2][4][8][16][32][64][128] ....
For example:
10 in binary is 0101 OR 0 + 2 + 0 + 8.
13 in binary is 1011 OR 1 + 0 + 4 + 8.
255 in binary is 11111111 OR 1 + 2 + 4 + 8 + 16 + 32 + 64 + 128
function dec2bin(dec){
return (dec >>> 0).toString(2).split('').reverse().join('');
}
This will give the decimal to binary:
let num = "1234"
console.log(num.toString(2));
This will give binary to decimal:
let num = "10011010010";
console.log(parseInt(num, 2));

toFixed function not working properly ( please give a reason not an alternative)

toFixed() function responding differently for float values.
For Example:
var a = 2.555;
var b = 5.555;
console.log(a.toFixed(2)); /* output is 2.56 */
console.log(b.toFixed(2)); /* output is 5.55 */
For 2.555/3.555 results are (2.56/3.56)
and
For other values(not sure for all values) it is showing #.55 (# refers to any number)
I am confused can any one help me out.
Thanks in advance.
Javascript uses a binary floating point representation for numbers (IEEE754).
Using this representation the only numbers that can be represented exactly are in the form n/2m where both n and m are integers.
Any number that is not a rational where the denominator is an integral power of two is impossible to represent exactly because in binary it is a periodic number (it has infinite binary digits after the point).
The number 0.5 (i.e. 1/2) is fine, (in binary is just 0.1₂) but for example 0.55 (i.e. 11/20) cannot be represented exactly (in binary it's 0.100011001100110011₂… i.e. 0.10(0011)₂ with the last part 0011₂ repeating infinite times).
If you need to do any computation in which the result depends on exact decimal numbers you need to use an exact decimal representation. A simple solution if the number of decimals is fixed (e.g. 3) is to keep all values as integers by multiplying them by 1000...
2.555 --> 2555
5.555 --> 5555
3.7 --> 3700
and adjusting your computation when doing multiplications and divisions accordingly (e.g. after multiplying two numbers you need to divide the result by 1000).
The IEEE754 double-precision format is accurate with integers up to 9,007,199,254,740,992 and this is often enough for prices/values (where the rounding is most often an issue).
Try this Demo Here
function roundToTwo(num) {
alert(+(Math.round(num + "e+2") + "e-2"));
}
roundToTwo(2.555);
roundToTwo(5.555);
toFixed() method depending on Browser rounds down or retain.
Here is the solution for this problem, check for "5" at the end
var num = 5.555;
var temp = num.toString();
if(temp .charAt(temp .length-1)==="5"){
temp = temp .slice(0,temp .length-1) + '6';
}
num = Number(temp);
Final = num.toFixed(2);
Or reusable function would be like
function toFixedCustom(num,upto){
var temp = num.toString();
if(temp .charAt(temp .length-1)==="5"){
temp = temp .slice(0,temp .length-1) + '6';
}
num = Number(temp);
Final = num.toFixed(upto);
return Final;
}
var a = 2.555;
var b = 5.555;
console.log(toFixedCustom(a,2));
console.log(toFixedCustom(b,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.

Converting a double to an int in Javascript without rounding

In C# the following code returns 2:
double d = 2.9;
int i = (int)d;
Debug.WriteLine(i);
In Javascript, however, the only way of converting a "double" to an "int" that I'm aware of is by using Math.round/floor/toFixed etc. Is there a way of converting to an int in Javascript without rounding? I'm aware of the performance implications of Number() so I'd rather avoid converting it to a string if at all possible.
Use parseInt().
var num = 2.9
console.log(parseInt(num, 10)); // 2
You can also use |.
var num = 2.9
console.log(num | 0); // 2
I find the "parseInt" suggestions to be pretty curious, because "parseInt" operates on strings by design. That's why its name has the word "parse" in it.
A trick that avoids a function call entirely is
var truncated = ~~number;
The double application of the "~" unary operator will leave you with a truncated version of a double-precision value. However, the value is limited to 32 bit precision, as with all the other JavaScript operations that implicitly involve considering numbers to be integers (like array indexing and the bitwise operators).
edit — In an update quite a while later, another alternative to the ~~ trick is to bitwise-OR the value with zero:
var truncated = number|0;
Similar to C# casting to (int) with just using standard lib:
Math.trunc(1.6) // 1
Math.trunc(-1.6) // -1
Just use parseInt() and be sure to include the radix so you get predictable results:
parseInt(d, 10);
There is no such thing as an int in Javascript. All Numbers are actually doubles behind the scenes* so you can't rely on the type system to issue a rounding order for you as you can in C or C#.
You don't need to worry about precision issues (since doubles correctly represent any integer up to 2^53) but you really are stuck with using Math.floor (or other equivalent tricks) if you want to round to the nearest integer.
*Most JS engines use native ints when they can but all in all JS numbers must still have double semantics.
A trick to truncate that avoids a function call entirely is
var number = 2.9
var truncated = number - number % 1;
console.log(truncated); // 2
To round a floating-point number to the nearest integer, use the addition/subtraction trick. This works for numbers with absolute value < 2 ^ 51.
var number = 2.9
var rounded = number + 6755399441055744.0 - 6755399441055744.0; // (2^52 + 2^51)
console.log(rounded); // 3
Note:
Halfway values are rounded to the nearest even using "round half to even" as the tie-breaking rule. Thus, for example, +23.5 becomes +24, as does +24.5. This variant of the round-to-nearest mode is also called bankers' rounding.
The magic number 6755399441055744.0 is explained in the stackoverflow post "A fast method to round a double to a 32-bit int explained".
// Round to whole integers using arithmetic operators
let trunc = (v) => v - v % 1;
let ceil = (v) => trunc(v % 1 > 0 ? v + 1 : v);
let floor = (v) => trunc(v % 1 < 0 ? v - 1 : v);
let round = (v) => trunc(v < 0 ? v - 0.5 : v + 0.5);
let roundHalfEven = (v) => v + 6755399441055744.0 - 6755399441055744.0; // (2^52 + 2^51)
console.log("number floor ceil round trunc");
var array = [1.5, 1.4, 1.0, -1.0, -1.4, -1.5];
array.forEach(x => {
let f = x => (x).toString().padStart(6," ");
console.log(`${f(x)} ${f(floor(x))} ${f(ceil(x))} ${f(round(x))} ${f(trunc(x))}`);
});
As #Quentin and #Pointy pointed out in their comments, it's not a good idea to use parseInt() because it is designed to convert a string to an integer. When you pass a decimal number to it, it first converts the number to a string, then casts it to an integer. I suggest you use Math.trunc(), Math.floor(), ~~num, ~~v , num | 0, num << 0, or num >> 0 depending on your needs.
This performance test demonstrates the difference in parseInt() and Math.floor() performance.
Also, this post explains the difference between the proposed methods.
What about this:
if (stringToSearch.IndexOfAny( ".,;:?!".ToCharArray() ) == -1) { ... }
I think that the easiest solution is using the bitwise not operator twice:
const myDouble = -66.7;
console.log(myDouble); //-66.7
const myInt = ~~myDouble;
console.log(myInt); //-66
const myInt = ~~-myDouble;
console.log(myInt); //66

Categories