Reputation: 19
This is my code:
switch(education){
case "no highschool diploma":
salary="25636";
break;
case "a high school diploma":
salary="35256";
break;
case "an Associate's degree":
salary = "41496";
break;
case "an Bachelor's degree":
salary = "59124";
break;
case "an Master's degree":
salary = "69732";
break;
case "an Professional degree":
salary = "89960";
break;
case "an Doctoral degree":
salary = "84396";
break;
}
console.log("In 2015, a person with "+education+" earned an average of "+ salary.toLocaleString("en-US") +"/year.");
Why is the result
In 2015, a person with a high school diploma earned an average of 35256/year.
instead of
In 2015, a person with a high school diploma earned an average of 35,256/year.
?
Upvotes: 0
Views: 82
Reputation: 5144
Different data types ( e.g. Number, String, Date ) often have their own implementation of .toLocaleString()
Because you call .toLocaleString()
on a String, you are currently using the default implementation as defined in the Object data type, which isn't being overwritten.
However if you want to use the version associated with a Number. You can cast a String to a Number using Number()
before you call .toLocaleString()
.
If you want to learn more read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toLocaleString
demo
const education = "a high school diploma";
switch(education){
case "no highschool diploma":
salary="25636";
break;
case "a high school diploma":
salary="35256";
break;
case "an Associate's degree":
salary = "41496";
break;
case "an Bachelor's degree":
salary = "59124";
break;
case "an Master's degree":
salary = "69732";
break;
case "an Professional degree":
salary = "89960";
break;
case "an Doctoral degree":
salary = "84396";
break;
}
console.log("In 2015, a person with "+education+" earned an average of " + Number(salary).toLocaleString("en-US") +"/year.");
Upvotes: 0
Reputation: 25
This is because salary="35256" is passed as a string. Try changing to salary=35256 and it should work
Upvotes: 0
Reputation: 261
you are working with String type, you need to convert to number first.
console.log("In 2015, a person with "+education+" earned an average of "+ Number(salary).toLocaleString("en-US") +"/year.");
Upvotes: 2
Reputation: 5874
Your values are strings, make them numbers:
const stringVariable = "12345";
const numberVariable = 12345;
console.log(stringVariable.toLocaleString("en-US")); // Logs 12345
console.log(numberVariable.toLocaleString("en-US")); // Logs 12,345
Upvotes: 2