Question about js variables | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 12

Question about js variables

how to have the first number of a variable ?

17th Sep 2017, 4:11 PM
Maxımee
Maxımee - avatar
4 Answers
+ 10
var num = 123; var firstDigit = num.toString().charAt(0); // not need of '+' // however, you can use '+' for implicit string casting, but then you don't need explicit use of method .toString(): var firstDigit = (''+num).charAt(0); // implicit string casting because concatenation with empty string (parenthesis are required to not be applied on resulted string, and not first on 'num' variable before concatenation... // Anyway, you need to cast it again (even implicitly) to number to use it as number... // Also, it's maybe more efficient to get it mathematically: var n = Math.abs(num); // use a unsigned copy (to preserve the value) if you want to handle negative numbers while (n>10) n = Math.ceil(n/10); // ... dividing by 10 and keeping only integer part will retrieve one digit to the right of the number at each iteration, until result is between 0 and 9 included. // Obviously, this is in case of decimal context: use the base you want instead 10 if you want to get digit in another representation than decimal ^^
17th Sep 2017, 5:01 PM
visph
visph - avatar
+ 7
Do you mean how to get first digit of variable stored number? var num = 123; var firstDigit = +num.toString().charAt(0);
17th Sep 2017, 4:24 PM
K137(){/**/};
K137(){/**/}; - avatar
+ 7
thannks for your responces 😁😁😁👍
19th Sep 2017, 5:00 PM
Maxımee
Maxımee - avatar
0
very good
19th Oct 2017, 4:23 AM
Natthakit Singkhan
Natthakit Singkhan - avatar