I want to have my calculator to display "0" when cleared or no other numbers have been entered but when I start adding numbers I want the 0 to be replaced. Currently when I enter any number it replaces the number on the display to the number entered.
this.currentDisplay = "0"
numberData(number) {
if (number === "." && this.currentDisplay.includes("."))
return
if (this.currentDisplay = "0") {
this.currentDisplay = this.currentDisplay.toString().replace("0", number.toString())
}
else {
this.currentDisplay = this.currentDisplay.toString() + number.toString()
}
}
You have an error on the this condition:
if (this.currentDisplay == "0") {
...
}
In your code you are assigning this.currentDisplay = 0, you should compare with == or better === to compare the types of the variables too.
Related
In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number :
When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller
When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger
When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message
When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?
function askValue() {
var answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
console.log("Please enter a valid number");
} else {
return answer;
}
}
function guessnumber() {
var secret_number = Math.floor(Math.random() * 10) + 1;
var guess = askValue();
var attempts;
var i = 0;
var resultMessage = "You won, you take";
while (win == false) {
attempts++;
if (guess < secret_number) {
console.log("The secret number is bigger");
i++;
} else if (guess > Secret_number) {
console.log("The secret number is smaller");
i++;
} else if (guess == secret_number) {
win = true;
}
console.log(resultMessage);
}
}
// call the function
guessnumber();
I make your code works by fixing many mistake and bugs some of them:
using var which is old and it's better use the keyword let to declare variable!
checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
many more...
if you don't understand sth do a comment and I will explain to you!
function askValue() {
let answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
alert("Please enter a valid number");
} else if (+answer < 1 || +answer > 10) {
alert("Please enter a number between 1 and 10");
} else {
return +answer;
}
}
// Better using `let` than `var`
function guessnumber() {
let secret_number = Math.floor(Math.random() * 10) + 1;
let guess = askValue();
let attempts = 0; //initialse attempts with zero
let i = 0;
let resultMessage = "You won, you take ";
let win = false; //declare win
while (win == false) {
attempts++;
if (guess < secret_number) {
alert("The secret number is bigger");
i++;
guess = askValue();
} else if (guess > secret_number) {
//s lowercase not capital
alert("The secret number is smaller");
i++;
guess = askValue();
} else if (guess == secret_number) {
win = true;
resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
alert(resultMessage);
} else {
guess = askValue();
}
}
}
// call the function
guessnumber();
I need to limit input to only one number and one decimal. For example to be able to put 9.5 but not 95.
Only thing I could think of is something like this:
let length = e.currentTarget.textContent.length;
if (length >= 3) {
console.log(length);
e.preventDefault();
}
Use this function
function numberValidator(input) {
if (input.length < 4)
if (typeof input == 'string') {
if (input.indexOf('.') == 0 || input.indexOf('.') == 2)
return false;
input = parseFloat(input).toFixed(1)
if (parseFloat(input) < 10) {
console.log(input);
return true
}
}
return false
}
if (numberValidator(e.currentTarget.textContent)) {
// setState
} else {
// e.preventDefault(); or dont set state
}
Let me know if it dosen't work,Upvote if works:-)
I'm trying to create a simple program that converts the numbers of hours provided by the user into seconds, and asks the user to reenter hours ,if he provides a string.It works fine when I enter non-positive number, but doesn't show any message if entered a string value.
Here is the code:
function convertToSeconds () {
var d = prompt("Enter any hour between 0-24","4");
if ( d<0 ){
alert("Please enter a number greater than zero");
convertToSeconds();
}
else if( typeof d == String ) {
/*Problem seems to be here*/
alert(d + " is not a valid number");
convertToSeconds();
}
else {
var seconds = 3600*parseFloat(d);
document.write(seconds);
}
};
convertToSeconds();
The prompt method only returns strings. You need to determine if the string can be converted to a positive integer between 0 and 24, so:
var d = prompt('Enter any hour between 0-24');
if ( /^(1?[0-9]|2[0-4])$/.test(d) ) {
alert('looks good');
} else {
alert('don\'t like that');
}
or you could do something like:
var d = Number(prompt('Enter any hour between 0-24'));
if (d == parseInt(d) && d > -1 && d < 25 {
// ok
}
// not ok
}
Just an issue with your code. typeof "any string" = "string" not String, also JS coerces a number in a string format to a number by default so I would recommend checking for string before number.
function convertToSeconds () {
var d = prompt("Enter any hour between 0-24","4");
if ( d<0 ){
alert("Please enter a number greater than zero");
convertToSeconds();
}
else if( isNaN(d) ) {
/*Problem seems to be here*/
alert(d + "is not a valid number");
convertToSeconds();
}
else {
var seconds = 3600*parseFloat(d);
document.write(seconds);
}
};
convertToSeconds();
I'm developing app in Titanium using Javascript and trying to realize the following check logic:
User has entered one value in range between 1 and 200, then he/she should enter second value in range between 1 and the first value(less or equal, but no more then the first value).
Here is my code:
var value_alert = ''; //First value
var value_remind = ''; //Second value (should be less or equal)
var default_value_alert = 10; //Default first value for TextField
var default_value_remind = 5; //Default second value for TextField
// handle and save the first value entered by user
function doOpenAlert(){
var input_text = Ti.UI.createTextField({
keyboardType: Ti.UI.KEYBOARD_PHONE_PAD
});
if(value_alert === ''){
input_text.value = default_value_alert;
} else {
input_text.value = value_alert;
}
var dialog = Ti.UI.createOptionDialog({
title : "Specified distance in the range 1-200 km",
androidView : input_text,
buttonNames : ['Ok', 'Cancel']
});
dialog.show();
dialog.addEventListener('click', function(e){
if(value_remind === ''){
value_remind = default_value_remind;
}
if(e.index == 0){ // Check is Ok pressed
// check_number = isInt(input_text.value);
if(input_text.value >= 1 && input_text.value <= 200){ // Check that the first value is in range
var toast = Titanium.UI.createNotification({
duration: 2000,
message: "Distance is " + input_text.value + " km."
});
toast.show();
value_alert = input_text.value; // Saving the first value entered by user
} else if(input_text.value == 0){
alert("The field is empty.");
} else if(!(input_text.value >= 1 && input_text.value <= 200)){
alert("Range is between 1 and 200 km.");
}
}
});
}
// handle and save the second value entered by user
function doOpenMinne(){
var input_text = Ti.UI.createTextField({
keyboardType: Ti.UI.KEYBOARD_PHONE_PAD
});
if(value_remind === ''){
input_text.value = default_value_remind;
} else {
input_text.value = value_remind;
}
var dialog = Ti.UI.createOptionDialog({
title : "Remind before number",
androidView : input_text,
buttonNames : ['Ok', 'Cancel']
});
dialog.show();
dialog.addEventListener('click', function(e){
if(value_alert === ''){
value_alert = default_value_alert;
}
if(e.index == 0){
// check_number = isInt(input_text.value);
if(input_text.value >= 1 && input_text.value <= value_alert){ // Check if the second value in is range between 1 and the first value
var toast = Titanium.UI.createNotification({
duration: 2000,
message: "Remind at " + input_text.value + " km."
});
toast.show();
value_remind = input_text.value; // Saving the second value entered by user
} else if(input_text.value == 0){
alert("The field is empty");
} else if(!(input_text.value >= 1 && input_text.value <= 200)){
alert("The range is between 1 and 200 km");
}
}
});
}
For example, it works well in the following combination:
1)
First value - 10;
Second value - 5;
2)
First value - 105;
Second value - 101;
And the main thing, if the first value is >= 100 , but the second is < 100 - it doesn't work.
It seems that conditions are correct, but works incorrect - can't find a mistake.
I think that the issue you're having is that you're comparing the values as strings rather than numbers. When you compare two strings, Javascript bases the comparison on the Unicode values of the characters in order. What does that mean for you? The short answer is, that while "90" < 200 is true because that comparison results in the "90" being coerced to 90, "90" < "200" is false because "9" is greater than "2".
In order to avoid this behavior, you need to convert one or both of your variables to numbers. This answer on converting strings into numbers shows a number of ways for you to do that, but in your case, I think that parseInt(input_text.value, 10) <= parseInt(value_alert, 10) would work fine for you.
a script returns either a number like 0.0580 so in x.xxxx format or a (x) for X units left.
I want to format the number 0.0580 and return 5.8 cent or return x units left.
Any ideas how to do that in javascript? Especially how do I format the x.xxxx?
In case the first x is not 0 I want to return e.g. 1.75$.
MS has written a nice plugin for jquery. it's especially useful if you're localizing. Give it a go:
http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx
I'm not sure if this can be used outside of jquery...
I may be spoiling you here, but whatever. Here's a function that I found somewhere at some point and have been recycling since. I haven't actually bothered to look much into it to figure out what it does exactly, but it has been rather useful:
function FormatMoneyAmount(starting_string, ending_string) {
//check validity of input (true = invalid, false = valid)
var valid_exp = new RegExp ('[^0-9,.$]', 'gi');
input_invalid = (typeof(ending_string) == 'undefined' && valid_exp.test(starting_string));
//check if more than 2 digits follow decimal or no decimal
decimal_invalid = typeof(ending_string) == 'undefined' && (starting_string.indexOf('.') > -1) && ((starting_string.length - starting_string.indexOf('.')) > 3);
if (input_invalid || decimal_invalid) {
ending_string = starting_string;
} else {
//remove commas, dollar signs
var replace_exp = new RegExp ('[,$]', 'gi');
starting_string = starting_string.replace(replace_exp, '');
//remove decimal if ending string not set, save for adding on later
var decimal_substring = '';
if (typeof(ending_string) == 'undefined' && starting_string.indexOf('.') > -1) {
decimal_substring = starting_string.substring(starting_string.indexOf('.'), starting_string.length);
remaining_string = starting_string.substring(0,starting_string.indexOf('.'));
} else {
remaining_string = starting_string;
}
//if string is already 3 characters or less, do nothing
if (remaining_string.length > 3) {
//separate last 3 characters of string from rest of string
var final_three = remaining_string.substring(remaining_string.length - 3, remaining_string.length);
remaining_string = remaining_string.substring(0, remaining_string.length - 3);
//if not first group of 3, add new group before old group with comma, else set to new group
ending_string = (typeof(ending_string) == 'undefined') ? final_three + ((typeof(decimal_substring) == 'undefined') ? '' : decimal_substring) : final_three + ',' + ending_string;
//call function again if more than 3 digits remaining to process, else add to end string
if (remaining_string.length > 3) {
ending_string = FormatMoneyAmount(remaining_string, ending_string);
} else {
ending_string = remaining_string + ',' + ending_string;
}
} else {
ending_string = (typeof(ending_string) == 'undefined') ? remaining_string : remaining_string + ',' + ending_string + ((typeof(decimal_substring) == 'undefined') ? '' : decimal_substring);
}
}
return ending_string;
}
The first thing to do is check the format of the string, since you will have two code paths depending on the result:
if (typeof num = "string" && num.slice(0,1) == "(" && num.slice(-1) == ")") {
// String is in the format (x), so we just need to return that number
return num.slice(1,-1) + " units left";
}
The next part is to check if the number is less than 1, indicating that it is cents and not whole dollars. If it is less than 1, multiplying it by 100 will give you the number of cents you're after:
if (+num < 1)
// 0.0580 * 100 = 5.8
return (num * 100) + " cents";
else
return +num + "$";