This question already has answers here:
How to convert decimal to hexadecimal in JavaScript
(30 answers)
Closed 5 years ago.
I'm writing some code(javascript) to change a base 10 number into base 16. I know base 16 have letters if the remainder is between 10 and 15. This is where I am having trouble. I can't change the remainder into the letter.
so far this what I have:
var mynum = 4053,remainder=[];
while (mynum > 0) {
total = mynum % 16;
remainder.push(total);
mynum = Math.floor(mynum / 16);
switch (total > 9 || total < 16) {
case total === 10:
total = "A";
break;
case total === 11:
total = "B";
break;
case total === 12:
total = "C";
break;
case total === 13:
total = "D";
break;
case total === 14:
total = "E";
break;
case total === 15:
total = "F";
break;
}
}
console.log(total,remainder)
Let's say "mynum" = 4053 then I would get 5,13,15. But I want to get 5,D,F.I also tried using a "for" loop but got the same thing. It feels like i'm close but just missing something something, Can someone please help me?
mynum is the actual number, total is the remainder, and "remainder" is where i put the remainder's in a list
hexString = yourNumber.toString(16);
it will convert base 10 to base 16
hexString = yourNumber.toString(16); is a better way to do it. But going by logic in your code, here is what you got wrong.
This remainder.push(total); statement should be after switch. In your code it is before switch.
mynum = 4053;
remainder = [];
while ( mynum > 0){
total = mynum % 16;
mynum = Math.floor(mynum / 16);
// remainder.push(total);
switch (total > 9 || total < 16){
case total === 10:
total = "A";
break;
case total === 11:
total = "B";
break;
case total === 12:
total = "C";
break;
case total === 13:
total = "D";
break;
case total === 14:
total = "E";
break;
case total === 15:
total = "F";
break;
}
remainder.push(total); // here
}
console.log(remainder);
Related
I'm working on switch statements at the moment, and have a little function below that turn a given numerical score into a grade. Or at least that's what it's supposed to do, but somehow it all goes wrong, and I'm not sure why!
function convertScoreToGrade(score) {
var grade = "";
switch(score) {
case 100>=score && score>=90: grade = "A";
break;
case 89>=score && score>=80: grade = "B";
break;
case 79>=score && score>=70: grade = "C";
break;
case 69>=score && score>=60: grade = "D";
break;
case 59>=score && score>=0: grade = "F";
break;
case score>100 || score<0: grade = "INVALID SCORE";
} return grade;
}
convertScoreToGrade(10);
For example, when I input the number 10 I only get an empty string, which suggests that the relevant case isn't evaluated. Any help would be appreciated.
Based on your example, here is a modification to make your code work
The big take away here is you match the parameter you pass into the switch statement. So passing a boolean value of true means that if your condition is true, that will be the case.
IMO, a switch statement is what you should use for this case. It's a small amount of cases (5), and is very readable for anyone who will work on or maintain this code at a later point.
function convertScoreToGrade(score) {
// Check for invalid scores first
if(typeof score !== 'number' || score < 0 || score > 100)
return "INVALID SCORE";
var grade = "";
// Pass a boolean value, remember we are matching this value
// EX: (score < 90) is true when score is 0 - 89
switch(true) {
case score < 60:
grade = "F";
break;
case score < 70:
grade = "D";
break;
case score < 80:
grade = "C";
break;
case score < 90:
grade = "B";
break;
case score <= 100:
grade = "A";
break;
}
// If you want partial grades
if(score % 10 <= 3 && score !== 100 )
grade += "-";
else if(score % 10 >= 7 || score == 100)
grade += "+";
return grade;
}
// These are small test cases to show you
// that convertScoreToGrade works as defined
console.log(convertScoreToGrade(-1));
console.log(convertScoreToGrade(101));
console.log(convertScoreToGrade('The dog ate it.'));
var i = 50;
while(i <= 100){
console.log(i, 'should be', convertScoreToGrade(i));
i += 4;
}
Bad solution that you might think of that is clearly worse than the alternative but I already typed it and I think it's helpful for you to understand that this is how you'd handle it with if statements. Please have mercy on me for posting such lousy code.
function convertScoreToGrade(score) {
var grade = "";
if(score>=0){
grade = "F";
}
if(score>=60){
grade = "D";
}
if(score>=70){
grade = "C";
}
if(score>=80){
grade = "B";
}
if(score>=90){
grade = "A";
}
if (score>100 || score<0){
grade = "INVALID SCORE";
}
return grade;
}
convertScoreToGrade(10);
function convertScoreToGrade(score) {
// scores is an array of objects
// Each element in the scores array has two properties, grade and score
// grade is the letter grade, score is the minimum score to achieve that grade
var i,l,scores = [{ grade: 'A', score: 90},
{grade: 'B',score : 80},
{grade: 'C',score: 70},
{grade: 'D',score: 60 }];
// Ensure score is between 0 and 100 inclusive
if (score < 0 || score > 100) {
return 'Invalid';
}
// Loop through all the scores and exit when the score is larger than the minimum
l = scores.length;
for (i=0;i<l;i++) {
if (score >= scores[i].score) {
return scores[i].grade;
}
}
// If the score was not found, the grade is an F
return 'F';
}
console.log(convertScoreToGrade(82));
console.log(convertScoreToGrade(90));
console.log(convertScoreToGrade(50));
This question already has answers here:
Expression inside switch case statement
(8 answers)
Closed 8 years ago.
The evaluations in the console print in the second line seem correct, but the switch statement won't work. And I am not getting any errors.
for (var i = 0; i < 100; i++) {
console.log(i % 3 === 0, i % 5 === 0);
switch (i) {
case i % 3 === 0:
console.log(i, " by three");
break;
case i % 5 === 0:
console.log(i, " by five ");
break;
}
}
http://jsfiddle.net/vL4omdxs/
As the comment said, that's not how you use switch/case.
You evaluate the condition in switch, then create different behaviours using cases.
Here is your code slightly modified (actually not so slightly, there's a small math twist):
var res = document.getElementById('r');
for (var i = 0; i < 100; i++) {
//console.log(i % 3 === 0, i % 5 === 0);
switch (i % 15) {
case 0:
r.innerHTML += i + " by three and five<br>";
break;
case 3:
case 6:
case 9:
case 12:
r.innerHTML += i + " by three<br>";
break;
case 5:
case 10:
r.innerHTML += i + " by five<br>";
break;
}
}
<div id="r"></div>
Just a hint (offtopic, but might help): switch/case is not the best approach for the 3/5 problem. See how much simpler it looks using ifs:
var res = document.getElementById('r');
for (var i = 0; i < 100; i++) {
res.innerHTML += "<br>" + i + ": ";
if (i % 3 == 0) {
res.innerHTML += "by three ";
}
if (i % 5 == 0) {
res.innerHTML += "by five ";
}
}
<div id="r"></div>
Case expressions are tested for strict equality so you need to change the switch from switch (1) to switch (true). However note that only one of the case blocks will be executed.
That's not the way to do the switch statement. It must be:
switch (i % 3) {
case 0:
...
break;
case 1:
...
break;
}
The expression within switch brackets is compared with the expression after case keyword. Take your code as example:
for (var i = 0; i < 100; i++) {
console.log(i % 3 === 0, i % 5 === 0);
switch (i) {
case i % 3 === 0: // if (i) equals (i % 3 === 0), run this branch
console.log(i, " by three");
break;
case i % 5 === 0: // if (i) equals (i % 5 === 0), run this branch
console.log(i, " by five ");
break;
}
}
And please remember, "equal" here means ===. Since your case expressions all return boolean, they'll never be equal to your i, which is a number.
I'm writing swtich javascript switch statement in JS file and figured out the problem whole day still cannot find the solution.
Here is my javascript file written in jQuery :
var percent = 20;
var widthbytes;
switch(percent)
{
case 0:
widthbytes=0;
break;
case (percent > 10 && percent < 20):
widthbytes=16;
break;
case (percent >=20 && percent < 30):
widthbytes=30;
break;
default:
widthbytes=0;
break;
}
average.width(widthbytes);
It always return to default instead of 30. Anything wrong with my codes ?
switch statement only check the value of variable and then give the result according to that value so your expression
case (percent > 10 && percent < 20):
return boolean value which is not not comparable to variable value. Use if-else to get the job done.
just make a bit change in your code.
You have switch(percent)**in your code, only change for this ***switch(true)*.
The reason for that is because the switch statement return a boolean value, this is why we need they have the same comparation, i.e. boolean vrs boolean.
For example the case 10: return one value; true or false.
I can't see a problems with #Carlos Marin's answer. This works:-
var percent = 10; //test values-> 10, 11, 19, 20, 21, 29, 30
var widthbytes;
switch(true){
// case 0:
// widthbytes=0;
// break;
case (percent > 10 && percent < 20):
widthbytes=16;
break;
case (percent >=20 && percent < 30):
widthbytes=30;
break;
default:
widthbytes=0;
break;
}
console.log(widthbytes);
switch statements don't work like that. Your second case is checked like this: if (percent == (percent > 10 && percent < 20)) ..., which will not yield the desired result.
You could use an if / elseif / else construct:
if (percent === 0) {
widthbytes = 0;
} else if (percent > 10 && percent < 20 {
widthbytes = 16;
} else if (percent >= 20 && percent < 30 {
widthbytes = 30;
} else {
widthbytes = 0;
}
Or you could use a function that turns the ranges into constants:
function getRange(percent) {
return Math.floor(percent/10);
}
switch(getRange(percent)) {
case 10:
widthbytes = 16;
break;
case 20:
widthbytes = 30;
break;
default:
widthbytes = 0;
}
Note that to get a cleaner implementation i assimilated your original case 0: into the default, since they both do the same thing. If that is not desirable, you need to change the getRange function to no longer return the same range for 0 as for any number between 0 and 10.
I am trying to write a JavaScript switch where the user enters a number from 1-100 and they receive a message based on what range the number falls into. This is what I have written so far.
I am doing this for an intro to programing class, and I don't fully understand how to get this to work, my problem is that I can't figure out how to show a range, ie: 1-25,
<script>
var number = prompt("Enter 1-100");
switch(number)
{
case 1-25:
document.write("1-25");
break;
case 26-50;
document.write("26-50");
break;
case 51-100:
document.write("51-75");
break;
case "4":
document.write("76-100");
break;
}
</script>
Just figuring it out with a little math is probably a better approach :
var number = prompt("Enter 1-100"),
message = ['1-25', '26-50', '51-75', '76-100'];
document.write(message[Math.ceil(number/25)-1])
FIDDLE
Divide the returned number with 25, round up to nearest whole number, which gives you 1,2,3 ... etc, and since array indices starts at zero, subtract 1.
EDIT:
If you have to do a switch, you'd still be better off with a little math, and not writing a hundred case's :
var number = prompt("Enter 1-100");
number = Math.ceil(number / 25 );
switch(number) {
case 1:
document.write("1-25");
break;
case 2:
document.write("26-50");
break;
case 3:
document.write("51-75");
break;
case 4:
document.write("76-100");
break;
}
FIDDLE
You can use conditions with switch like this:
var number = prompt("Enter 1-100");
switch (true) {
case number >= 1 && number <= 25:
alert("1-25");
break;
case number >= 26 && number <= 50:
alert("26-50");
break;
case number >= 51 && number <= 75:
alert("51-75");
break;
case number >= 76 && number <= 100:
alert("76-100");
break;
}
http://jsfiddle.net/dfsq/T3zJR/
You cannot use ranges in switch statements. To check whether a value is contained in a range, you need to compare against lower and upper bounds:
number = parseInt(number, 10);
if (number >= 1 && number <= 25)
document.write("1-25");
else if (number >= 26 && number <= 50)
document.write("26-50");
else if (number >= 51 && number <= 75)
document.write("51-75");
else if (number >= 75 && number <= 100:
document.write("76-100");
else
document.write(number+" is not a valid number between 1 and 100");
Of course, as the number of if-elses grows, you should look for an alternative. An algorithmic solution would be the simplest (dividing by 25 and rounding to find the 25-multiple interval the number is contained in):
number = parseInt(number, 10);
var range = Math.floor((number-1)/25);
if (range >= 0 && range < 4)
document.write( (1+range*25) + "-" + (1+range)*25);
If you can't use that (for example because of erratic intervals) a for-loop (or even a binary search) over an array of interval boundaries would be the way to go (as demonstrated by #jfriend00).
If you want simple ranges of 25, you can do this:
if (number < 1 || number > 100)
document.write("out of range");
else {
var low = Math.floor(number / 25) * 25 + 1;
var high = low + 24;
document.write(low + "-" + high);
}
You need a single value to match a case, or a switch takes longer than if elses...
you can get the range before switching-
var number = prompt("Enter 1-100", '');
var s= (function(){
switch(Math.floor((--number)/25)){
case 0: return "1-25";
case 1: return "26-50";
case 2: return "51-75";
default: return "76-100";
}
})();
alert(s);
Here's a table driven approach that allows you to add more items to the table without writing more code. It also adds range checking.
<script>
var breaks = [0, 25, 50, 75, 100];
var number = parseInt(prompt("Enter 1-100"), 10);
var inRange = false;
if (number) {
for (var i = 1; i < breaks.length; i++) {
if (number <= breaks[i]) {
document.write((breaks[i-1] + 1) + "-" + breaks[i]);
inRange = true;
break;
}
}
}
if (!inRange) {
document.write("Number not in range 1-100");
}
</script>
I have an array. One of the values in that array responses[1] is an integer. This integer can be from 1 to whatever number you want. I need to get the last number in the integer and determine based on that number if I should end the number with 'st', 'nd', 'rd', or 'th'. How do I do that? I tried:
var placeEnding;
var placeInt = response[1]; //101
var stringInt = placeInt.toString();
var lastInt = stringInt.charAt(stringInt.length-1);
if (lastInt == '1'){
placeEnding = 'st';
} else if (lastInt == '2'){
placeEnding = 'nd';
} else if (lastInt == '3'){
placeEnding = 'rd';
} else {
placeEnding = 'th';
}
but that did not work. Every time I tried printing placeEnding it was always 'th' no matter if it should have been 'st', 'rd', or 'nd'. When I tried printing placeInt, stringInt, or lastInt they all printed as " instead of the number. Why is this so? When I print responses[1] later on in the script I have no problem getting the right answer.
If all you want is the last digit, just use the modulus operator:
123456 % 10 == 6
No need to bother with string conversions or anything.
Here you go:
var ends = {
'1': 'st',
'2': 'nd',
'3': 'rd'
}
response[1] += ends[ response[1].toString().split('').pop() ] || 'th';
As others have pointed out, using modulus 10 is more efficient:
response[1] += ends[ parseInt(response[1], 10) % 10 ] || 'th';
However, this'll break if the number has a decimal in it. If you think it might, use the previous solution.
In my rhino console.
js> (82434).toString().match(/\d$/)
4
Alternate way to get lastInt is:
var lastInt = parseInt(stringInt)%10;
switch lastInt {
case 1:
placeEnding = 'st';
break;
case 2:
placeEnding = 'nd';
break;
case 3:
placeEnding = 'rd';
break;
default:
placeEnding = 'th';
}
I noticed I wanted to use the st/nd/rd/th in dates, and just noticed there is an exception between 10 and 20 with the eleventh, twelfth and so on, so I came to this conclusion:
if (n % 10 === 1 && (n % 100) - 1 !== 10) {
return "st";
} else if (n % 10 === 2 && (n % 100) - 2 !== 10) {
return "nd";
} else if (n % 10 === 3 && (n % 100) - 3 !== 10) {
return "rd";
}
return "th";