javascript outcome of toFixed().length - javascript

I have question about ".toFixed().length. I have here a if statement: if (num.toFixed(2).length > 4) {". And i dont understand the outcome of the result.
i thougth it woud count the length of the string. Because toFixed covert the number to a string. But i dont get the outcome. I hope you have a ans because i cant find it on the internet or my teachers ad school dont know it ether.
Thank you for your time,
num = 1234.567
>>> 1234.567
num2 = num.toFixed(2).length
>>> 7 // why is this 7??
num2
>>> 7
num = 1234
>>> 1234
num2 = num.toFixed(2).length
>>> 7
num = 2
>>> 2
num2 = num.toFixed(2).length
>>> 4// and this 4??

What you describe in your question is essentially the expected behavior of toFixed().
It will always round the passed number to two decimals and convert it to a string always showing these two decimals, even if they're 0.
You can try several more results in this small sample on ideone.
Back to your initial question:
if (num.toFixed(2).length > 4)
This expression could be translated to "string representation is longer than 4 characters".
Since we already mentioned the two decimals and the decimal point always being there, all string results will end in .## (where # could be any digit). That's a string length of 3 characters.
This essentially means there have to be at least two more characters before the decimal point for this statement to become true:
#.## would be 4 characters, which still doesn't fulfill the condition.
'##.##' works. These are 5 characters, which is definitely longer than 4.
So this means any number equal to or bigger than 10 would fulfill this statement. Considering there's rounding involved, any number greater than 9.95 should work for this.
So why not write if (num > 9.95)? Simply because that's only part of the answer.
There are negative numbers as well. If you evaluate Number(-1).toFixed(2) you'll get the string -1.00, which is 5 characters already!
But what about rounding? Here it gets even more interesting. If you run Number(-.01).toFixed(2) one would assume that this is rounded to 0.00. This is kinda true, but JavaScript will retain the negative prefix, resulting in -0.00. This is once again a string with 5 characters!
So combining these two observations we can say that the expression in your if() clause is true under either of these two conditions:
The number is bigger than 9.5 (i.e. it's rounded to 10 or larger)
The number is negative.
So one could replace the rather cryptic/complicated expression with the following term and get the same results:
if (num < 0 || num >= 9.5)

num = 1234.567
>>> 1234.567
num2 = num.toFixed(2).length
>>> 7 // why is this 7??
Here you want to know the length of the string so it's giving you the string length. If you do .tofixed(2) on 1234.567 it will remain the same.

Related

Plus One - Leet code Problem (easy )- All the test cases passed except one in javascript

I guess my solution has passed all the test cases but failed on one.
Plus one- leetcode problem
Problem:
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
Constraints:
1 <= digits.length <= 100
0 <= digits[i] <= 9
digits does not contain any leading 0's.
My solution:
var plusOne = function(digits) {
let arrToStr=digits.join('');
arrToStr++;
let strToArr = arrToStr.toString().split('').map((x)=>parseInt(x));
return strToArr;
};
Failed on this test cases:
Input:
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
Output:
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,0,0,0]
Expected:
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]
Is there anything I am doing wrong? Or Is it because of javascript? As I have read that javascript is not good for Competitive programming because it has some drawbacks.
Integer in JavaScript can only represent up to 9,007,199,254,740,991 (https://stackoverflow.com/a/49218637/7588455)
6,145,390,195,186,705,543 is larger than that.
I recommend using BigInt as an alternative.
A possible solution would look like this:
https://pastebin.com/NRHNYJT9 (Hidden so I don't spoiler you)
Here is my solution, though it might not exactly shine concerning its performance:
function plusOne(digits: number[]): number[] {
let digitsCombined = BigInt(digits.join(''));
return (++digitsCombined).toString().split('').map(Number);
};

JS Preserve decimals ending in zeroes [duplicate]

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

remove leading 0 before decimal point and return as a number- javascript

Problem
I need to return a number in the format of .66 (from an entered value which includes the leading zero, e.g. 0.66)
It must be returned as an integer with the decimal point as the first character.
what method in JavaScript can help me do this?
What have I tried?
I've tried converting it toString() and back to parseInt() but including the decimal point makes it return NaN.
I've tried adding various radix (10, 16) to my parseInt() - also unsuccessful
Sample Code
const value = 0.66;
if(value < 1) {
let str = value.toString().replace(/^0+/, '');
// correctly gets '.66'
return parseInt(str)
}
//result NaN
Expectations
I expect an output of the value with the leading 0 removed
e.g. 0.45 --> .45 or 0.879 --> .879
Current Observations
Output is NaN
I tried a quick solution, you may try to do this:
let a = 0.45;
// split on decimal, at index 1 you will find the number after decimal
let b = a.toString().split('.')[1];
Issue #1:
0.66 is not an Integer. An Integer is a whole number, this is a floating-point number.
Issue #2:
You cannot have a number in JavaScript that starts with a decimal point.
Even if you change your parseInt to be parseFloat, it will still return 0.66 as a result.
What you're asking just isn't possible, if you want a number to start with a decimal point then it has to be a string.

What's the function of the "|" (pipe) operator? [duplicate]

This question already has answers here:
Using bitwise OR 0 to floor a number
(7 answers)
Closed 8 years ago.
I have this line that I copied from another place:
Total += parseFloat($(this).val())|0;
What's the function of the operator |? When I change the number, I get different results.
The | in JavaScript is an integer bitwise OR operator. In that context, it strips off any fractional portion returned by parseFloat. The expression parseFloat($(this).val()) will result in a number with (potentially) a fractional component, but then |0 will convert it to an integer number, OR it with 0 (which means it won't change), and so the overall result is to get a whole number.
So functionally, it truncates the fractional portion off the number. -1.5 becomes -1, and 1.5 becomes 1. This is like Math.floor, but truncating rather than rounding "down" (Math.floor(-1.5) is -2 — the next lowest whole number — rather than -1 as the |0 version gives us).
So perhaps that's why it was used, to chop off (rather than "floor") the fractional portion of the number.
Alternately, it could be a typo. The author of that code might have meant to write this (note || rather than |):
Total += parseFloat($(this).val()) || 0;
That defends against the possibility that $(this).val() returns "" or similar, resulting in parseFloat returning NaN. It uses the curiously-powerful || operator to return 0 rather than NaN in that case. (And there's an advertisement for putting spaces around your operators.) Would have to know the context of the code to say whether truncating to a whole number (|) makes sense when adding to Total, or if they were just defending the NaN case.
The | operator in javascript is the bitwise or operator
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators
This operator treats the operands as 32 bit integers and for every bit returns 1 if either is 1 and 0 otherwise.

JavaScript | operator [duplicate]

This question already has answers here:
Using bitwise OR 0 to floor a number
(7 answers)
Closed 8 years ago.
Anyone able to explain what "|" and the value after does? I know the output for 0 creates sets of 13, the numbers, 3, 2, 1, 0. But what about | 1, or | 2.
var i = 52;
while(i--) {
alert(i/13 | 0);
}
It is the bitwise OR operator. There is both an explanation and an example over at MDC. Since doing bitwise OR with one operand being 0 produces the value of the other operand, in this case it does exactly nothing rounds the result of the division down.
If it were written | 1 what it would do is always print odd numbers (because it would set the 1-bit to on); specifically, it would cause even numbers to be incremented by 1 while leaving odd numbers untouched.
Update: As the commenters correctly state, the bitwise operator causes both operands to be treated as integers, therefore removing any fraction of the division result. I stand corrected.
This is a clever way of accomplishing the same effect as:
Math.floor(i/13);
JavaScript developers seem to be good at these kinds of things :)
In JavaScript, all numbers are floating point. There is no integer type. So even when you do:
var i = 1;
i is really the floating point number 1.0. So if you just did i/13, you'd end up with a fractional portion of it, and the output would be 3.846... for example.
When using the bitwise or operator in JavaScript, the runtime has to convert the operands to 32 bit integers before it can proceed. Doing this chops away the fractional part, leaving you with just an integer left behind. Bitwise or of zero is a no op (well, a no op in a language that has true integers) but has the side effect of flooring in JavaScript.
It's a bitwise operator. Specifically the OR Bitwise Operator.
What it basically does is use your var as an array of bits and each corresponding bit is with eachother. The result is 1 if any of them is 1. And 0 if both are 0.
Example:
24 = 11000
10 = 1010
The two aren't of equal length so we pad with 0's
24 = 11000
10 = 01010
26 = 11010
24 | 10 = 26
Best way to learn this is to readup on it.
That is the bitwise OR. In evaluating the expression, the LHS is truncated to an integer and returned, so | is effecively the same as Math.floor().

Categories

Resources