Have a quick JS question. What is the difference between math.round and parseInt?
I made a JS script to sum the inverses of prompted numbers:
<script type="text/javascript">
var numRep = prompt("How many repetitions would you like to run?");
var sum = 0;
var count = 0;
var i = 1; //variable i becomes 1
while (i <= numRep) {// repeat 5 times
var number = prompt("Please enter a non zero integer");
if(number==0){
document.write("Invalid Input <br>");
count++;
}
else{
document.write("The inverse is: " + 1/number + "<br>");
sum = sum + (1/parseInt(number)); //add number to the sum
}
i++; //increase i by 1
}
if (sum==0){
document.write("You did not enter valid input");}
else { document.write("The sum of the inverses is: " + sum); //display sum
}
</script></body></html>
and it uses parseInt. If I wanted to makeit use math.round, is there anything else I need to do so that It knows to limit the number of decimal places accordingly?
In other words, does math.round have to be formatted in a certain way?
The two functions are really quite different.
parseInt() extracts a number from a string, e.g.
parseInt('1.5')
// => 1
Math.round() rounds the number to the nearest whole number:
Math.round('1.5')
// => 2
parseInt() can get its number by removing extra text, e.g.:
parseInt('12foo')
// => 12
However, Math.round will not:
Math.round('12foo')
// => NaN
You should probably use parseFloat and Math.round since you're getting input from the user:
var number = parseFloat(prompt('Enter number:'));
var rounded = Math.round(number);
Math.round will round the number to the nearest integer. parseInt will assure you that the value is a number
So what you will need is something like this:
number = parseInt(number);
if ( isNan(number) || number == 0 ){
document.write("Invalid Input <br>");
count++;
}
This will assure you that the use has put in a number
Math.round expects a number, parseInt expects a string.
Use parseInt('12345', 10) for parsing 10-based numbers.
http://www.javascripter.net/faq/convert2.htm
Related
Can someone show me how to write a function that adds 0's after the decimal if less than four digits appear after the decimal until 4 decimal spots long and trim digits from far right of decimal in excess of 4. These are strings. Don't want any rounding. For display only, not calculations. So for example:
719.843797 should remove last two digits to be 719.8437
21.947 should add one 0 to be 21.9470
1.3456 no change
Using toFixed or any sort of multiplication may result in rounding problems. Treating number as a string allows to avoid them. The function below passes all your given usecases. But this is kinda hacky. Though I'm not sure if there is a better way to fit your requirements.
function truncate4(x) {
var parts = x.toString().split('.'); // this is not i18n proof :(
var integral = parts[0];
var decimal = parts[1] || ''; // might be integer
return integral + '.' + (decimal + '0000').substr(0, 4)
}
console.log(truncate4(719.843797));
console.log(truncate4(21.947));
console.log(truncate4(1.3456));
This function should match
function arrondir(num){
var str = num.toString();
var index = str.indexOf(".");
var decimal = str.substr(index+1);
var integer = str.substr(0, index);
if (decimal.length < 4)
for (var i = 0; i < 5 - decimal.length; i++)
decimal = decimal.concat("0");
else decimal = decimal.substr(0,4);
return integer.concat(".").concat(decimal);
}
console.log(arrondir(719.84)); // 719.8400
console.log(arrondir(719.84657963657)); // 719.8465
So I have a number like 5467. I want my code to return 546.
I tried taking the last number and subtracting it from the original number but I get 5460 instead of 546.
Combine / with %:
(5467 - (5467 % 10)) / 10
564
Sounds like you also need to divide my 10. You could do something like this:
var number = 5467;
number = number - (number % 10); // This will subtract off the last digit.
number = number / 10;
console.log(number); // 546
We first use the modulo operator % to get the last digit, and we subtract it from number. That reduces the number from 5467 to 5460. Now to chop off the last digit (which is guaranteed to be a 0) we divide by 10 and get 546.
Written more concisely you could do:
number = (number - ( number % 10)) / 10;
There's a few things you can do the most concise being:
Math.floor(num / 10);
Or, convert to a string, remove the last character and convert back to number.
parseInt(num.toString().slice(0, -1));
If string representation would be fine for you then one other way is
var num = 5467,
cut = (num/10).toFixed(); // <-'547'
Well... warning..! i have to say toFixed() method rounds if necessary. So in this particular example it doesn't work.
I dont mind some of the other answers, but i feel that this maybe too fixed on it being a number.
Which it is, but you want to remove the last digit/char, regardless of the number, so why not substr?
http://www.w3schools.com/jsref/jsref_substr.asp
var s = 5467;
s = s.toString().substr(0, s.toString().length - 1);
console.log(s)
or even easier:
var s = (5467).toString();
s = s.substr(0, s.length - 1);
console.log(s)
These dont take into account single digit numbers, so passing in 1 would return blank. To answer that you could simply do a check like:
var s = (1).toString();
if(s.length > 1)
s = s.substr(0, s.length - 1);
console.log(s)
Also, similar question to:
Remove last digits from an int
Remove the last digits of a number (not string)
Removing the last digits in string
To truncate digits from the right hand side until the number is less than 30, keep dividing by 10 and rounding down until a suitable value is reached:
var n = 12341235;
while (n > 30) n = n/10|0;
document.write(n);
The greater than and division operations will coerce n to a number, so it can be a number or string. If ToNumber(n) results in NaN (e.g. n = 'foo'), then the value of n is not modified.
You can simply divide the number by 10 and parseInt()
var num = 5467;
num = parseInt(num/10);
Update :
To repeat the process until the answer is less than 30, use while loop as
var num = 5467;
while(num >= 30) {
num = parseInt(num/10);
}
document.write(num);
I have a function to sum values with same ID; jsFiddle. This works, but not if is a decimal value, like a money value. (10,05 + 1.005,10, example)
$('#button-cart').on('click', function() {
var MaxSelectionNum = "7";
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
console.log(parseInt($(this).val()));
sum += parseInt($(this).val()) || 0;
});
if (sum < MaxSelectionNum)
{
$(".errorQuantity").html("Please select 7 meals").show();
}
else
{
$(".errorQuantity").html("You have select greater than 7: meal count: " + sum).show();
}
});
How can we fix it?
Use parseFloat instead of parseInt when dealing with decimal values.
parseInt() function parses a string argument and returns an integer or NaN. If not NaN, the returned value will be the integer representation of the string passed in.
parseFloat() function parses a string argument and returns a floating point number or Nan(If the string expression cannot be converted to a numerical value).
Here is a working sample.
You must use parseFloat:
just replace your current code with the following one:
$('#button-cart').on('click', function() {
var MaxSelectionNum = "7";
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
console.log(parseFloat($(this).val()));
sum += parseFloat($(this).val()) || 0;
});
if (sum < MaxSelectionNum)
{
$(".errorQuantity").html("Please select 7 meals").show();
}
else
{
$(".errorQuantity").html("You have select greater than 7: meal count: " + sum).show();
}
});
This gonna help you :)
I've updated your script a bit (js lines 10-16)
https://jsfiddle.net/La18Lcns/10/
If you want to use number taplate such as
1.142,32
23.456,5
1.500
First you need to conver it to float format
1142.32
23456.5
1500
Than you use parseFloat() instead ParseInt()
$('#button-cart').on('click', function()
{
var MaxSelectionNum = "7";
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
console.log(parseFloat($(this).val()));
sum += parseFloat($(this).val()) || 0;
});
if (sum < MaxSelectionNum)
{
$(".errorQuantity").html("Please select 7 meals").show();
}
else
{
$(".errorQuantity").html("You have select greater than 7: meal count: " + sum).show();
}
});
My assignment for Intro to Javascript is to: "Write a function that accepts two numbers and returns a random number between the two values." It seems easy enough until I attempt to prompt the variables to input, at which point the output seems incorrect.
This is code that is most recommended for finding a random number between two ints, in this case 1 and 6:
function getRandomizer(bottom, top) {
return function() {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
}
var rolldie = getRandomizer(1, 6);
document.write(rolldie());
The output I get is what it should be, a random integer between 1 and 6. However my assignment is to prompt for the numbers, which can be anything. So I do this, using 10 and 1 as example numbers:
var max = prompt("input 10");
var min = prompt("input 1");
function getRandomizer(bottom, top) {
return function() {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
}
var rolldie = getRandomizer(min, max);
document.write(rolldie());
The output: 961. Second try: 231. etc. If I set the variables max and min directly to 10 and 1, the code works perfectly, returning numbers between 1 and 10. But for some reason, prompting input and then entering the exact same numbers gives completely different output. Why does this happen and how can I fix it?
The reason this happens is that the prompts are being treated as strings. So you're actually getting numbers between 1101 and 1.
You can ensure the vars min and max are numbers by using parseInt:
var max = parseInt(prompt("input 10"));
Try this Code below:
var max = Number(prompt("input 10"));
var min = Number(prompt("input 1"));
I am beginner to javascript and i am getting unexpected output
here is the code
<script type="text/javascript">
function add(a,b)
{
x = a+b;
return x;
}
var num1 = prompt("what is your no.");
var num2 = prompt("what is another no.")
alert(add(num1,num2));
</script>
it should give output as a sum of two number entered by us on prompting but it is simply concatenating the two number and popping the output
This is because the prompt function returns a String and not a Number. So what you're actually doing is to request 2 strings and then concatenate them. If you want to add the two numbers together you'll have to convert the strings to numbers:
var num1 = parseFloat(prompt("what is your no."));
var num2 = parseFloat(prompt("what is another no."));
or simpler:
var num1 = +prompt("what is your no.");
var num2 = +prompt("what is another no.");
prompt returns a string, not a number. + is used as both an addition and concatenation operator. Use parseInt to turn strings into numbers using a specified radix (number base), or parseFloat if they're meant to have a fractional part (parseFloat works only in decimal). E.g.:
var num1 = parseInt(prompt("what is your no."), 10);
// radix -----^
or
var num1 = parseFloat(prompt("what is your no."));
When you prompt the user, the return value is a string, normal text.
You should convert the strings in numbers:
alert(add(parseInt(num1), parseInt(num2));
The return value of prompt is a string. So your add function performs the + operator on 2 strings, thus concatenating them. Convert your inputs to int first to have the correct result.
function add(a,b)
{
x = parseInt( a ) + parseInt( b );
return x;
}
In addition to the already provided answers: If you're using parseInt() / parseFloat(), make sure to check if the input in fact was a valid integer or float:
function promptForFloat(caption) {
while (true) {
var f = parseFloat(prompt(caption));
if (isNaN(f)) {
alert('Please insert a valid number!');
} else {
return f;
}
}
}
var num1 = promptForFloat('what is your no.');
// ...