Best way convert number to string javascript? [duplicate] - javascript

This question already has answers here:
What's the best way to convert a number to a string in JavaScript?
(25 answers)
Closed 5 years ago.
What is the best way to convert a number to string in javascript?
I am familiar with these four possibilities:
Example 1:
let number = 2;
let string1 = String(number);
Example 2
let number = 2;
let string2 = number.toString();
Example 3
let number = 2;
let string3 = "" + number;
Example 4
let number = 2;
let string4 = number + "";
All examples giving the same result, but what is the best option to choose based on Performance? Or is it personal preference?
Thanks for answering.

The problem with approach #2 is that it doesn’t work if the value is null or undefined.
1st , 3rd and 4th which are basically equivalent.
""+value: The plus operator is fine for converting a value when it is surrounded by non-empty strings. As a way for converting a value to string, I find it less descriptive of one’s intentions. But that is a matter of taste, some people prefer this approach to String(value).
String(value): This approach is nicely explicit: Apply the function String() to value. The only problem is that this function call will confuse some people, especially those coming from Java, because String is also a constructor.

Related

Javascript array join does not work correctly [duplicate]

This question already has answers here:
Issue with combining large array of numbers into one single number
(3 answers)
Closed 1 year ago.
I have the following array and I want to join it into a number
const arr = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
const digits = arr.join("") //6145390195186705543
const digitsToNumber = +arr.join("") //6145390195186705000
console.log(digits);
console.log(digitsToNumber);
You can see that the join function works. However, when I try to convert it into a number, it shows a weird value. Do you guys know why it happened that way?
As stated in the comments, the value is too large for JavaScript and is truncated.
We can use BigInt to prevent this. Use with caution!
const arr = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
const digits = arr.join('');
const digitsToNumber = +arr.join("");
const bigDigitsToNumber = BigInt(arr.join(''));
console.log(digits); // 6145390195186705543
console.log(digitsToNumber); // 6145390195186705000
console.log(bigDigitsToNumber.toString()); // 6145390195186705543
They will log different results because you are exceeding Number.MAX_SAFE_INTEGER - the highest value JS can safely compare and represent numbers.
One method to check if you are ever exceeding the limit (besides remembering the value) is Number.isSafeInteger()
Number.isSafeInteger(digitsToNumber); //false
From the docs: For larger integers, consider using the BigInt type.
To convert your concatenated string into a number you could use parseInt("123") method.
const number= parseInt(digitsToNumber)
However because of your number is too big or could be bigger, Javascript can not handle that numbers which contains more than 16 digit. If you also have a problem like that you can use some external big number libraries like BigNumber.Js.
Edit: According to Teemu's comment, you could also use link native big integer handling library.

Testing if a specific sequence of numbers is somewhere in a integer javascript [duplicate]

This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
What's the best way to convert a number to a string in JavaScript?
(25 answers)
Closed 2 years ago.
I know that this question was asked about in PHP but I could not find anything in javascript.
I have a random number generated between 000(yeah it is just three zero's but it is shown that way from how the number is generated) and 999999999 and I want to test true or false for if whether it includes a specific sequence of numbers like 777, 9000, 28, or the like of any length and from any beginning of numbers...
for example, finding 289 in 678342891 or 728987699 would be true, and finding 289 in 678529187 or 023829564 would be false.
is this possible, and how would I do it?
you can use .includes method in JS after transforming both the number and the other number to strings using .toSting method
let n = 12345589;
let sub = 55;
let sub2 = 25;
function isSeq(number, sub){
number = number.toString(10);
sub = sub.toString(10);
return number.includes(sub);
}
console.log(isSeq(n, sub));
console.log(isSeq(n, sub2));
Check whether your test number is a substring in your long random number. Since you have mentioned that 000 is a value, this tells me that it is a string already(no need to call toString() for it)
var random=678342891;
var search1=289;
var search2=777;
console.log( random.toString().indexOf(search1.toString()) != -1 );//true
console.log( random.toString().indexOf(search2.toString()) != -1 );//false
A function to test it would look like so:
function test(random,search){
return random.toString().indexOf(search.toString()) != -1
}

Is there a better way to achieve this? '000000'.slice(0, -'434'.length) + '434' = '000434' [duplicate]

This question already has answers here:
convert '1' to '0001' in JavaScript [duplicate]
(4 answers)
Pad a number with leading zeros in JavaScript [duplicate]
(9 answers)
Closed 3 years ago.
Yep, the title says pretty much everything. Basically I want a default X-digit number which is all zeros. Then, from this number, I want to replace the last characters with other numbers. For example, if I have '434', and the default is '000000', the result should be '000434'.
In Ruby, this is the equivalent of doing '%.6d' % 434 and it returns '000434'. If the number I want to save has more than 6 digits, I just use that number instead. I realized that as I'm working with strings I could use this solution:
let base = '000000'
let str = '434'
console.log(base.slice(0, -str.length) + str)
Buuut, even if it's a simple approach, I don't know if it's the best. What daya' think?
For compatibility with older JS environments, you can depend only on a simpler slice:
(base + str).slice(-6)
For modern ones, padStart is available:
str.padStart(6, '0') // or String(num)
JavaScript has string.padStart(length, padString)
let str = '434'
const updated = str.padStart(6, '0')
console.log(updated)

Adding two big numbers in javascript [duplicate]

This question already has answers here:
How to deal with big numbers in javascript [duplicate]
(3 answers)
Closed 3 years ago.
I've been trying to add the following numbers using javascript;
76561197960265728 + 912447736
Sadly, because of rounding in javascript it will not get the correct number, I need the number as a string.
I've tried removing the last few digits using substr and then adding the two numbers together and then putting the two strings together, sadly this doesn't work if the first of the number is a 1.
function steamid(tradelink){
var numbers = parseInt(tradelink.split('?partner=')[1].split('&')[0]),
base = '76561197960265728';
var number = parseInt(base.substr(-(numbers.toString().length + 1))) + numbers;
steamid = //put back together
}
steamid('https://steamcommunity.com/tradeoffer/new/?partner=912447736&token=qJD0Oui2');
Expected:
76561198872713464
For doing operations with such big integers, you should use BigInt, it will correctly operate on integers bigger than 2ˆ53 (which is the largest size that normal Number can support on JS
const sum = BigInt(76561197960265728) + BigInt(912447736);
console.log(sum.toString());
Edit 2020: This API still not widely supported by some browsers, so you may need to have a polyfill, please check this library

Variables and math operators [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Strange javascript addition problem
I know there's obviously a solution for this, and I've done it before, but I can't remember it and now I can't find it.
​<div>1</div>​​​​​​​​
$(function() {
var number = $('div').text();
var math = number + 2;
$('body').text(math);
});​
http://jsfiddle.net/G5zdx/
number is not being treated as an integer so math's value is "12" instead of "3". How can I correct this?
There are many ways, but
var math = (1 * number) + 2;
is a simple one. Whether you should be detecting possible ill-formed non-numbers depends on the nature of the rest of your code.
The parseInt() function is useful, but it probably should be called with 10 as its second argument to avoid interpreting numbers that begin with zero as octal constants instead of decimal. Also, parseInt() will not treat a string like "23skidoo" as an error, which may or may not be OK in your application.
​<div>1</div>​​​​​​​​
$(function(){
var number = parseInt($('div').text(), 10);
var math = number+2;
$('body').text(math);
});​
You can parse a string as an int using parseInt(string[, radix]).
Your code would look as follows
$(function(){
var number = $('div').text();
var math = parseInt(number, 10)+2;
$('body').text(math);
});
Source: http://www.javascripter.net/faq/convert2.htm

Categories

Resources