What does parameter in Array toString do? - javascript

I saw a code like this. I looked up MDN but there's no mention about toString having parameters. What does 3 do inside n.toString(3)?
function solution(n) {
n = n.toString(3).split('').reverse().join('')
return parseInt(n, 3)
}

This is Number.prototype.toString(), not Array.prototype.toString(). It takes radix as an optional parameter.
An integer in the range 2 through 36 specifying the base to use for representing numeric values.
Your code converts n to base-3. If you want to convert a number to binary, you'd do n.toString(2)
const n = 16,
bases = [2, 3, 4, 10, 16]
console.log(
bases.map(radix => n.toString(radix))
)

It is an optional parameter when converting number to string:
Optional. Which base to use for representing a numeric value. Must be
an integer between 2 and 36. 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

This is the Radix (a number represent base-3 numeral system or any other numeral systems). For example if you put 2 instead of 3 this function convert the result into the binary system.
you can put from 2 - 36 in it as the parameter.And the default value is 10 and this parameter is completely optional.
test this one:
var x = 10;
x.toString(2); // output: "1010"

Related

Truncate a number

function truncDigits(inputNumber, digits) {
const fact = 10 ** digits;
return Math.trunc(inputNumber * fact) / fact;
}
truncDigits(27624.399999999998,2) //27624.4 but I want 27624.39
I need to truncate a float value but don't wanna round it off. For example
27624.399999999998 // 27624.39 expected result
Also Math.trunc gives the integer part right but when you Math.trunc value 2762439.99 it does not give the integer part but gives the round off value i.e 2762434
Probably a naive way to do it:
function truncDigits(inputNumber, digits) {
return +inputNumber.toString().split('.').map((v,i) => i ? v.slice(0, digits) : v).join('.');
}
console.log(truncDigits(27624.399999999998,2))
At least it does what you asked though
Try this:
function truncDigits(inputNumber, digits){
return parseFloat((inputNumber).toFixed(digits));
}
truncDigits(27624.399999999998,2)
Your inputs are number (if you are using typescript). The method toFixed(n) truncates your number in a maximum of n digits after the decimal point and returns it as a string. Then you convert this with parseFloat and you have your number.
You can try to convert to a string and then use a RegExp to extract the required decimals
function truncDigits(inputNumber: number, digits: number) {
const match = inputNumber.toString().match(new RegExp(`^\\d+\\.[\\d]{0,${digits}}`))
if (!match) {
return inputNumber
}
return parseFloat(match[0])
}
Note: I'm using the string version of the RegExp ctor as the literal one doesn't allow for dynamic params.

parse integer with javascript using parseInt and a radix

I am doing an online test and it asks me to write basic javascript code.
It asks me to parse a numberic string and convert it to a number of a different base. It needs me to return -1 if for whatever reason the conversion cannot be done.
I have written this:
function convert(strNumber, radix) {
var result = parseInt(strNumber, radix);
if(isNaN(result))
{return -1;}
return result;
}
Then it runs my code through various tests and all pass. Except one.
Apparently convert("ASD", 15) should be invalid according to the test and it expects it to be -1.
But Javascript happily converts it to number 10
I tried various things such as to add a try{}catch{} block and other things, but javascript never complains about converting "ASD" to base 15.
Is the test wrong, or is parseInt wrong?
By the way strNumber can be any base under 36.
So for instance:
convert("Z", 36) is 35
As I stated in the comment, parseInt will convert up to the point where it fails. So "A" is valid in that radix and "S" is not. So you would need to add a check.
var nums = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".substr(0, radix)
var re = new RegExp("^[" + nums + "]+$","i")
if (!re.test(strNumber)) {
return -1
}
parseInt is behaving normally and is converting the letter A into 10 in base 15 (similar to how hex uses A for the number 10). The S and D are discarded, as parseInt accepts this type of malformed input.
From the parseInt documentation:
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.
As per official documentation the parseInt function behaves as following
For radices above 10, the letters of the alphabet indicate numerals
greater than 9. For example, for hexadecimal numbers (base 16), A
through F are used.
and
If parseInt encounters a character that is not a numeral in the
specified radix, it ignores it and all succeeding characters and
returns the integer value parsed up to that point.
Thus to prevent invalid arguments from being parsed they have to be validated first
function convert(strNumber, radix) {
if (isValidRadix(radix) && isValidInteger(strNumber, radix))
return parseInt(strNumber, radix);
return -1;
}
function isValidInteger(str, radix) {
var letters = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'].slice(0,radix);
str = str.toUpperCase();
for (var i=0; i<str.length; i++) {
var s = str.charAt(i);
if (letters.indexOf(s) == -1) return false;
}
return true;
}
function isValidRadix(radix) {
// 16 up to HEX system
return radix > 0 && radix <= 16;
}
console.log(convert("ASD", 15));
console.log(parseInt("ASD", 15));
console.log(convert("AAA", 15));

value more than not read in if condition in javascript

I m getting two textboxes value as 5 and 10.
so i m validating them on the following if condition
var textboxvalue1 = $('#textboxvalue1' + counter).val();
var textboxvalue2 = $('#textboxvalue2' + counter).val();
if (textboxvalue1 < textboxvalue2) {
alert("error");
}
textboxvalue1 = 10
textboxvalue2 = 5
its showing an alert in this case.which it shud nt show.bt when textboxvalue1 is less than 10,it works fine.
Actually your .val() returns string you try to convert it as integer so use parseInt() in your context and check.
The parseInt() function parses a string and returns an integer.
Note:
The radix parameter is used to specify which numeral system to be
used, for example, a radix of 16 (hexadecimal) indicates that the
number in the string should be parsed from a hexadecimal number to a
decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal) If the
string begins with "0", the radix is 8 (octal). This feature is
deprecated If the string begins with any other value, the radix is 10
(decimal)
var textboxvalue1= parseInt($('#textboxvalue1'+counter).val(), 10);
var textboxvalue2= parseInt($('#textboxvalue2'+counter).val(), 10);
if (textboxvalue1 < textboxvalue2) {
alert("error");
}
You have to convert your input strings to numbers like this:
var textboxvalue1=parseInt($('#textboxvalue1'+counter).val());
var textboxvalue2=parseInt($('#textboxvalue2'+counter).val());
The values are being interpreted as strings by JavaScript, not numbers. Wrap them in parseInt or parseFloat before comparing them.
Use ParseInt Because var return string default. Or you can use parseFloat
var textboxvalue1= parseInt($('#textboxvalue1'+counter).val(), 10);
var textboxvalue2= parseInt($('#textboxvalue2'+counter).val(), 10);
if (textboxvalue1 < textboxvalue2) {
alert("error");
}

Multiplying an array with a single value by a number?

Why does JavaScript allow you to multiply arrays with a single numeric value by another numeric value or by another array with a single numeric value?:
[3] * 3;
// 9
[3] * 2;
// 6
[3] * [3];
// 9
[1, 2] * 2
// NaN
I would expect NaN to be returned every time but as my experiments in Chrome have demonstrated this is not the case.
Is this the expected behavior? Does this behavior make sense? If so, why?
[3] * 3;
The following steps are taken:
array is converted to a string [3] => "3"
the string is converted to a number Number("3") => 3
3 * 3 gives 9
Similarly, for [1, 2] * 2:
array is converted to a string [1, 2] => ""1,2"
the string is converted to a number Number("1,2") => NaN
NaN * 3 gives NaN
For ECMA freaks among us ;) start here and follow the path multiplicative operator => ToNumber => ToPrimitive => [[DefaultValue]](number) => valueOf => toString
What is happening here is that [3] is being coerced into a String type, which is just "3". Then in "3" * 3 the String value "3" gets converted into the number 3. You finally end up with 3 * 3, which evaluates to 9.
You can see this behavior if you do [3].toString() * 3 or "3" * 3, which also gives you 9,
So the following steps happen:
[3] * 3
[3].toString() * 3
"3" * 3
Number("3") * 3
3 * 3
9
In the case [1, 2], you eventually end up with "1, 2". But Number("1, 2") results in a NaN and a number multiplied with a NaN results in NaN.
http://ecma-international.org/ecma-262/5.1/#sec-15.4.4.2
Since Array.prototype.valueOf is not available, it falls back to using the String version (as per http://ecma-international.org/ecma-262/5.1/#sec-9.9)
The toString renders an array with a single element as the value of the element (so [3].toString() is 3)
//Say to increase each element by 10%, we may use the following:
let arr=[];
let array = [100, 200, 500, 1000];
array.forEach((p,i)=>arr[i]=(p*110/100));
console.log(arr);
//expected [110,220,550,1100]

Javascript: Comparing two float values [duplicate]

This question already has answers here:
Javascript float comparison
(2 answers)
Closed 6 months ago.
I have this JavaScript function:
Contrl.prototype.EvaluateStatement = function(acVal, cfVal) {
var cv = parseFloat(cfVal).toFixed(2);
var av = parseFloat(acVal).toFixed(2);
if( av < cv) // do some thing
}
When i compare float numbers av=7.00 and cv=12.00 the result of 7.00<12.00 is false!
Any ideas why?
toFixed returns a string, and you are comparing the two resulting strings. Lexically, the 1 in 12 comes before the 7 so 12 < 7.
I guess you want to compare something like:
(Math.round(parseFloat(acVal)*100)/100)
which rounds to two decimals
Compare float numbers with precision:
var precision = 0.001;
if (Math.abs(n1 - n2) <= precision) {
// equal
}
else {
// not equal
}
UPD:
Or, if one of the numbers is precise, compare precision with the relative error
var absoluteError = (Math.abs(nApprox - nExact)),
relativeError = absoluteError / nExact;
return (relativeError <= precision);
The Math.fround() function returns the nearest 32-bit single precision float representation of a Number.
And therefore is one of the best choices to compare 2 floats.
if (Math.fround(1.5) < Math.fround(1.6)) {
console.log('yes')
} else {
console.log('no')
}
>>> yes
// More examples:
console.log(Math.fround(0.9) < Math.fround(1)); >>> true
console.log(Math.fround(1.5) < Math.fround(1.6)); >>> true
console.log(Math.fround(0.005) < Math.fround(0.00006)); >>> false
console.log(Math.fround(0.00000000009) < Math.fround(0.0000000000000009)); >>> false
Comparing floats using short notation, also accepts floats as strings and integers:
var floatOne = 2, floatTwo = '1.456';
Math.floor(floatOne*100) > Math.floor(floatTwo*100)
(!) Note: Comparison happens using integers. What actually happens behind the scenes: 200 > 145
Extend 100 with zero's for more decimal precision. For example use 1000 for 3 decimals precision.
Test:
var floatOne = 2, floatTwo = '1.456';
console.log(Math.floor(floatOne*100), '>', Math.floor(floatTwo*100), '=', Math.floor(floatOne*100) > Math.floor(floatTwo*100));
Comparing of float values is tricky due to long "post dot" tail of the float value stored in the memory. The simplest (and in fact the best) way is: to multiply values, for reducing known amount of post dot digits to zero, and then round the value (to rid of the tail).
Obviously both compared values must be multiplied by the same rate.
F.i.: 1,234 * 1000 gives 1234 - which can be compared very easily. 5,67 can be multiplied by 100, as for reducing the float comparing problem in general, but then it couldn't be compared to the first value (1,234 vel 1234). So in this example it need to be multiplied by 1000.
Then the comparition code could look like (in meta code):
var v1 = 1.234;
var v2 = 5.67;
if (Math.round(v1*1000) < Math.round(v2*1000)) ....

Categories

Resources