+prompt vs prompt in JavaScript - javascript

Is it good to use +prompt instead of just regular prompt in JavaScript if I want only integer numbers to be typed in my prompt window? Does it say something like that about +prompt in the JavaScript standard/rules ?

Well this is what happen's when you add plus before prompt, i.e. as below,
Eg :- 1
var a = prompt("Please enter a number");
console.log(a);
typeof(a);
Now in eg (1) when you enter a number and if you check that in console, it show a number but as that number is in-between double-quote, so in JavaScript it's a string, that's what it will show in typeof too when you console that.
Eg :- 2
var a = +prompt("Please enter a number");
console.log(a);
typeof(a);
Now when you console the var a and typeof a of eg(2) the result differs as we have added + before prompt. So this time we get our prompt input value as number and not string. Try you will understand what I'm saying.

No.
The unary plus operator will convert the response in to a Number, not an integer.
It could give you a floating point value, it could give you NaN.
If you want an integer then you need to check the response and then put in some error recovery for cases where the response is not what you want.
For example: If it is a floating point value, then you might want to just use Math.floor to convert it. If it is NaN then you might want to prompt the user again.

The effect of +promt("...") is that the result of the promt command will be cast to a number.
This is a nice hack, but not a clean solution.
I would recommend to assign the user input to a variable, then check it and in case it doesn't match the requirements, throw an exception or error message.
var
input = prompt("Please enter a positive number"),
inputNum = parseInt(input, 10);
if (isNaN(inputNum) || inputNum < 1)
alert("You did not enter a positive number.");

So putting a + before any data type converts it into a number.
I tried this:
typeof(+"100") ==> number
typeof(+"12.34") ==> number
typeof(+true) ==> number
typeof(+false) ==> number
Things got really weird when I experimented with the undefined data type. e.g.:
x = +undefined
typeof(x) ==> Number whilst value of variable x is NaN

+prompt() is just a + before a prompt(), it's like writing +"3" or +"10". It just tries to cast the outcome to a number.

Related

Multiplcation in Javascript

I have a script for taking data entered into a Price field on my editor and splitting it across a Pounds and Pence field based on the . symbol.
Now I've been asked if I could multiply the Price field by 1.2 and display the result in the Pounds field. The pence field would no longer be needed.
I have no idea if multiplication can even work and especially using decimal points... Can anyone explain how I should rewrite the below?
$('#price1').keyup(function(event) {
if ($('#price1').val().indexOf('.') != -1){
$('#pence1').val($('#price1').val().substr($('#price1').val().indexOf('.') + 1, $('#price1').val().lengh));
$('#pound1').val($('#price1').val().substr(0, $('#price1').val().indexOf('.')));
}else{
$('#pound1').val($('#price1').val());
};
});
Some things to remark:
Your current solution has a spelling mistake for length.
Don't locate the decimal point. Instead use native JavaScript capabilities to evaluate the input. You can use parseFloat(), Number() or the unary plus operator for that.
Once you have the numeric value, you can multiply using the * operator. As multiplication will also convert its operands to number, you don't even need the previous advice, although it is still good practice to first do the conversion to number and then do the arithmetic.
Use the input event instead of the keyup event: input is not always the result of key events (think copy/paste via context menu, drag/drop, other devices...)
Here is the proposed solution:
$('#price1').on("input", function(event) {
var num = +$('#price1').val(); // convert to number using unary plus operator
// multiply, format as string with 2 decimals, and convert back to number
num = +(num * 1.2).toFixed(2)
$('#pound1').val(num); // output
});

Javascript templete literals not working with random number generator

I'm trying to generate a random number and then if the user enters the same num he can move forward otherwise it will generate another random number. But the template literal to generate random num (a) is not working.
var a = Math.floor(Math.random()*10); // Random num generator
var userInput = alert('Enter the numbers: ${a}'); // User input
while ( userInput !== a){ // Loop
alert("Try Again!");
userInput = alert('Enter the numbers: ${a}');
};
There are a few things that can be improved in your code.
Naming your number variable a instead of n is confusing.
Math.floor can be shorted to ~~ in your case (not every case).
You get user input from prompt, not alert, which merely shows a message.
You're using the strict equality !== operator to compare your random number with the user's input, which will always be a number in String form. So even if they enter the correct number, it will be interpreted as incorrect, since '3' is not strictly equal to 3. You have to use != instead.
There's no need for a userInput variable since you're only doing one thing with it. Just inline the prompt inside the condition of the while loop.
Since n never changes, declare it with const so that if you accidentally try to change it later, you will get an error to bring this to your attention.
As someone noted in the comments, string literals use `, not '.
const n = ~~(Math.random() * 10);
while (prompt(`Enter the number: ${n}`) != n) {
alert('Try again!');
};

Input box with accounting.js formatting not letting me input decimal numbers

On my website satoshindex.com when I try and type a number with a decimal point into the top input box, it automatically deletes the decimal point. It also doesn't let me highlight the input with Ctrl-A or use the arrow keys to move to a different digit in the number.
I think it has something to do with accounting.js.
Here is the relevant code from my website:
var SAT = 0.00000001;
var BIT = 0.000001;
var MBIT = 0.001;
var BTC = 1;
var currentUnit = BTC;
I know it has something to do with these lines in the btcConvert and usdConvert functions because when I delete them the issue goes away but no commas are used to separate the numbers.
var decimals = decimalPlaces(input.value);
input.value = accounting.formatNumber(input.value, decimals)
I think the issue is that btcConvert is called every time you type in the input box and formatNumber is deleting the decimal place, but without formatNumber in btcConvert I can't get it to add commas to the number when it is above 999, same in USD convert.
You can actually enter a decimal number like 1234.5 if you type the .5 really fast or if you copy-paste it into the input field. With normal typing speed, 1234. always turns into 1234 before you can add the 5. As you suspect, accounting.js is simplifying the 1234. to 1234 because that is what it considers to be the canonical format.
So you want to make it possible for the user to type 1234.0 and have it automatically formatted to 1,234.0 in the input field. I see three possible approaches:
Modify the accounting.js code. Edit accounting.formatNumber so that it doesn't discard the decimal point when it's the final character of input.value.
Don't use accounting.js to format the input field. Replace the call to accounting.formatNumber with a call to a formatting function that you write yourself.
A quick and dirty solution: Don't modify accounting.js and keep the call to accounting.formatNumber, but if input.value had a decimal point at the end and you get back a string without the decimal point, stick it back on.
One way to apply the quick and dirty approach to btcConvert is to replace this line:
input.value = accounting.formatNumber(input.value, decimals)
With this:
var formatted = accounting.formatNumber(input.value, decimals);
if (input.value.indexOf('.') == input.value.length - 1 &&
input.value.length != 0 &&
formatted.charAt(formatted.length - 1) != '.') {
formatted += '.';
}
input.value = formatted;
The check for input.value.length != 0 is necessary because if input.value is the empty string, indexOf will always return -1, which is equal to input.value.length - 1 for empty input.value.

correct number format detection separator

I have
var value = $120,90
var value = $1,209.00
currently I replace the first case with
value = value.replaceAll(",", ".").replaceAll("[^0-9.]*", "");
which gives me that I am looking for: the integer 12090
with the second case I run in a problem however like this. How can I solve this in Javascript?
You may modify you regexp.
value = value.replace(/,/g, ".").replace(/^\D|\.(?!\d*$)/g, "");
First will replace ',' to '.' and the 2nd replace NON-digit symbols in the beginning of the string and all dots EXCEPT the last one with the empty string. Then use parseFloat.
To be sure completely it's better to create a template for data input and don't allow users to enter values in an invalid format.
I cannot see how you can make an algorithm work unless you insist that everyone enters dollars and cents. The only option I can think of is to use locale to determine the number separator.
Could you use the answer from this thread?
How can I remove the decimal part from JavaScript number?
They use Math.floor() (round down), Math.ceil() (round up) or Math.round() (round to nearest integer).

Getting NaN when adding variables which consists of another variables

var dml = 30
var dd = parseFloat(document.getElementById("DriverD").value) <----- Only numbers like 10
var dm = dd-dml
alert((dd - dml) * 0.75) <----- This works
alert(dm * 0.75) <----- This returns NaN
alert(typeof(dm)) <----- This show that dm is a Number
I'm not sure why I keep getting NaN. I already tried parseFloat and parseInt but still showing NaN when multiplying a variable (dm) which consists of variables (dd-dml). dm is the result of subtracting dml with dd or 10-30. Please share your solutions.
I'm new here and I need help, please don't troll :) I am trying to add a cost calculator to my website.
It seems fine to me.
I want to tell another possible problem: You dont check if document.getElementById("DriverD").value is a number or not. If a user enters a string or other type, it will cause a problem.
Try this
Two operands must be convert to parseFloat
<input type="text:" value="10" id="DriverD" />
var dml = parseFloat(30);
var dd = parseFloat(document.getElementById("DriverD").value);
var dm = dd-dml;
alert(dm * .10);
Result is -.2
The only reason you could get NaN here is that the value of dd is NaN. Because the value of dm is defined as dd - dml and the value of dml is a Number value, 30.
parseFloat() always returns a Number value. The - operator converts its operands to Number only if necessary. So the value of dm must by definition be a Number value.
However, NaN is a Number value (typeof NaN === "number"), and it is "toxic": once an operand is NaN, the result of all following arithmetic operations is NaN.
That means that parseFloat() must have returned NaN, which means that the argument to parseFloat() could not be interpreted as the prefix of a decimal number representation.
One common reason for that is that the user has typed thousands separators (which are not supported) or a decimal comma while only a decimal point is supported.
Try this one
var dml = 30;
var dd = parseFloat(document.getElementById("DriverD").value) ; <----- Only numbers like 10
var dm=0;
dm = dd-dml;
alert((dd - dml) * 0.75); <----- This works
alert(dm * 0.75); <----- This returns NaN
alert(typeof(dm)); <----- This show that dm is a Number
I am a newbie but I think it is the type error, solution:
var someV = parseInt(document.getElementById("some-v-id").value, 10) || 0,
parseInt(value, 10) - you know because you used parse float, but two pipes and zero might prevent you from NaN as JavaSrcipt might be treating 0 as a string.

Categories