This question already has answers here:
How can I round a number in JavaScript? .toFixed() returns a string?
(16 answers)
Convert 0 to 0.00 as number
(1 answer)
Is there any way to maintain an integer with .00 in javascript?
(1 answer)
Closed 3 years ago.
In JavaScript, is it possible to "lock" a decimal number, to preserve "floating point" numbers that end with zeroes?
Example, I have 2 different numbers, like this: (pseudo code)
let a = 1.0;
let b = 1.00;
a === b // true, should be false, because different decimals.
print(a) // "1", should be "1.0"
print(b) // "1", should be "1.00"
(should also be different from a "true int" 1)
I want them to identify as different from each other, because they have different amount of zeroes at the end.
But stupidly "efficient" JavaScript rounds them both down to "integer" 1 & therefore they are equal.
I am aware of the Number.toFixed(Number) & Number.toPrecision(Number) functions, but to use them like this I have to first calculate the length of the number, which I can't because JavaScript have already rounded away the zeroes.
I have also been thinking of "cutting" off the number at the decimal point & store them in an array... but again, rounded to an "int" without a decimal point.
(Yes, I know that the concept of "float" doesn't exist in JS, I use it here to diferentiate between numbers with or without decimals).
Thanks for any help.
To compare 2 variables of indefinite type, the variables must be cast internally. This is the problem. Because both A and B are a set with the thickness 1.
Therefore the result is True.
However, if you want to compare the number of zeros, you have to compare them as a string.
So either you declare the variables with
let a = '1.0';
let b = '1.00';
or you cast the variables using
a.toString() === b.toString();
Related
This question already has answers here:
using division operator (/) on strings in javascript
(3 answers)
Closed last year.
Check the code Image
How I am getting Output = 1 for console.log('6'/'6') in Javascript. It should not be able to devide two strings
When a mathematical operator that only makes sense on numbers is applied to two expressions, both expressions are coerced to numbers first..
4. Let lnum be ? ToNumeric(lval).
5. Let rnum be ? ToNumeric(rval).
7. 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
...
which then calls Number::divide with lnum and rnum.
The only exception is +, which will only add if both sides are numbers - otherwise, it will coerce both sides to strings and then concatenate.
This question already has answers here:
Truncate number to two decimal places without rounding
(43 answers)
Closed 2 years ago.
is there a way to have 2 numbers after comma without rounding the value. I want the exact value. Math.round() and toFixed() give the value rounded.
You can do the workaround with help of Math.ceil() and Math.floor() functions.
Another way, is treat is as an string and use .slice()
i.e:
number = number.slice(0, number.indexOf(".")+3); //this should give you 2 decimals
Number(number); //Convert it to "Number" again, so you can operate with it
Solution without type conversions
While solving the issue, you should bear in mind that bouncing back and forth between data types may cost you some of app performance wasted
Instead, I'd suggest to modify input number directly:
shift the dot n positions to the right by multiplying your number by 10 in power of n (10**n)
cut off what's left after dot, using bitwise OR (|) that implicitly turns the float into integer
divide the result by 10 in power of n to shift the dot n positions back to the left
Following is a quick live-demo:
const num = 3.14159265,
precision = 4,
limitPrecision = (n,p) => (0|n*10**p)/10**p
console.log(limitPrecision(num, precision))
.as-console-wrapper{min-height:100%;}
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 4 years ago.
I'm trying to get the number of digits of a number in javascript, but I'm running into some edge cases with the equations I've found online.
Here's what I'm using, from this site.
getNumDigits(val){
return val === 0 ? 1 : Math.floor(Math.log(Math.abs(val)) / Math.LN10 + 1);
}
But the problem with this is, if you put in a number like 1000, you somehow get a javascript rounding error where the value comes out like 3.999997
I've noticed that, as long as your number isn't between -1 and 1, you can just add 1 to the val in the Math.abs(val) and it will appropriately set the number of digits, but it just seems messy.
I've tried just converting the val into a string, and getting the length, but that doesn't work in the case of, say, a decimal, where you're using something like 0.2 - as it will say the length is 3.
What's a good equation / function to use?
Making the number a string and using a regex to only count the digits can work.
function getNumDigits(val) {
return (`${val}`.match(/\d/g) || []).length
}
console.log(getNumDigits(2.5245234))
This question already has answers here:
Javascript - Leading zero to a number converting the number to some different number. not getting why this happening?
(2 answers)
Closed 5 years ago.
I was sorting a string/array of integers in lexicographical order. A case came when i had to sort a string containing "022" using array.sort. I don't know why it is equating that equal to "18" when being printed.
var l = [022,12];
l.sort();
(2) [12, 18] => output
What is the reason behind this and how to correct it?
I recommend to "use strict"; so that 022 will produce a syntax error instead of octal number:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_octal
This isn't specific to the sort. If you just type 022 into a console, you'll get back 18. This is because 022 is being interpreted as an OctalIntegerLiteral, instead of as a DecimalLiteral. This is not always the case however. Taking a look at the documentation:
Note that decimal literals can start with a zero (0) followed by another decimal digit, but If all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. This won't throw in JavaScript, see bug 957513. See also the page about parseInt().
EDIT: To remove the leading 0s and interpret the 022 as a decimal integer, you can use parseInt and specify the base:
parseInt("022", 10);
> 22
This question already has answers here:
Javascript addition and subtraction with a string value
(8 answers)
Closed 8 years ago.
Why such thing would happen in Javascript?
'5'+3 = 53
'5'-3 = 2
This is happening because + operator is overloaded. If any operand is a string, string concatenation is performed. If you have two numbers, addition is performed.
In other words
2+3=5
while '2'+3='23' and 2+'3'='23'.
On the other hand, for the - operator, it is not overloaded in such a way and all operands are converted to numbers.
'8'-2=6
because - is not overloaded and operand '8' will be converted to 8. Hence, we get 6.
For further information on this, please have a look here and read the paragraphs 11.6.1 and 11.6.2.
String concatenation is done with + so Javascript will convert the first numeric 5 to a string and concatenate "5" and "3" making "53".
You cannot perform subtraction on strings, so Javascript converts the second numeric i.e. "3" to a number and subtracts 3 from 5, resulting in "2" as the result.