+ 12
Question about js variables
how to have the first number of a variable ?
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 ^^
+ 7
Do you mean how to get first digit of variable stored number?
var num = 123;
var firstDigit = +num.toString().charAt(0);
+ 7
thannks for your responces đđđđ
0
very good