Rounding number in javascript up to some decimal point
If we want to round a number up to certain decimal point, in that case Math.round(x) won’t work . For example if x = 5.67, then Math.round(x) will be 6. In certain cases we want rounding up to some decimal places (y). To do that We need to do the following 1. Multiply given number by 10^y 2. Now round the result using Math.round. e.g. Math.round(x*10^y) 3. Divide number by 10^y. If x = 10.567 and we want to format x up to two points of decimal. We need to do the following
var result = Math.round(x * 100)/100;
And the output will be 10.57
Create a random number between 1 to 10 excluding 3, 5, and 9.?
This could be done by creating a random number and checking it if it doesn’t belong to 3, 5 and 9.
Random random=new Random();
int intVal=random.nextInt(11);
while(intVal==3 || intVal==5 || intVal==9){
intVal=random.nextInt(11);
}
System.out.println(intVal);
Secondly we can have an array initialized with [1,2,4,6,7,8,10] and now generate a number between 0 to 6 and return the element corresponding to that index.
Implement strtok() function. (It tokenizes the string )
Implementation of strtok
char* strtok(char *s, const char *delim) {
static char *old = NULL;
char *token;
if(! s) {
s = old;
if(! s) {
return NULL;
}
}
if(s) {
s += strspn(s, delim);
if(*s == 0) {
old = NULL;
return NULL;
}
}
token = s;
s = strpbrk(s, delim);
if(s == NULL) {
old = NULL;
} else {
*s = 0;
old = s + 1;
}
return token;
}