Validate decimal in javascript - javascript

hi i want to know how to write a validation code for a number with two decimal places for example 45.80
function submitform4()
{
var min=00.01;
var max = 100.00;
var num = parseInt(document.getElementById('valid').value);
console.log(num);
if (min > num || max < num) {
alert(num + ' is not between ' + min + ' and ' + max);
return false;
}
}
this is something i copied from my work and thought i could change it but didnt really work.

Well, this is what I'd do, If I understand correctly.
This addresses a few issues:
JavaScript doesn't like the numeric value 00.01. Use 0.01 instead
use parseFloat on your input value. parseInt will round to an integer
return true if successful (not undefined)
function submitform4() {
var MIN = 0.01;
var MAX = 100.00;
var input = document.getElementById('AgeGrade');
var inputValue = parseFloat(input.value);
var is_valid = (MIN > inputValue || MAX < inputValue);
if (is_valid) {
input.value = inputValue.toFixed(2); // set to 2 decimal places
return true
} else {
alert(inputValue + ' is not between ' + MIN + ' and ' + MAX);
return false;
}
}

You could do something like this:
function submitForm(numberToEvaluate){
var min = 0.0;
var max = 100;
//Instead of being passed in
//This would be grabbed from DOM element
var num = numberToEvaluate;
console.log(num);
if (min > num || max < num) {
alert(num + ' is not between ' + min + ' and ' + max);
return false;
}
}
submitForm(-1);
submitForm(37);

The code looks fine (almost), depending on how you intend to use i the function.
If you are using the function as a validation before you submit, like if(submitform4()) then you need to add return true; to the end of the function to return true unless the answer is false.

I would try parseFloat() :
function submitform4()
{
var min = parseFloat("00.01");
var max = parseFloat("100.00");
var num = parseFloat("200.20");
console.log(num);
if (min > num || max < num) {
alert(num + ' is not between ' + min + ' and ' + max);
console.log('false');
}
}
submitform4();
See Feedle
Else you certainly have error :
Uncaught SyntaxError: Unexpected number
See not working Feedle

Related

I want to write javascript code to get a addition countdown

so basically this the prompt:
Addition countdown
you enter a number and the code should be adding a number while countingdown, for example if the user enter 10, then the result should be:
10 + 9 + 8 + 7 + 6 + 5 + 4 +3 +2 +1=55.
This is what I have so far:
var num = Number(prompt("Enter a Number Greater than zero"));
while (num > 0){
first = num;
second = num-=1;
document.write(first + " +" + second + " +");
value = first + num;
document.write(value)
num--;
}
but I keep on getting something like this:
4 +3 +72 +1 +3 (let's say 4 is the number the user inputs)
I'm stuck can someone please help me????!!
You can keep total in one variable outside of while loop.
var num = Number(prompt("Enter a Number Greater than zero"));
var total = 0;
while (num > 0) {
total += num;
document.body.innerHTML += (num == 1 ? num + ' = ' + total : num + ' + ');
num--;
}
You could change the algorithm a bit, because for the first value, you need no plus sign for the output.
var num = Number(prompt("Enter a Number Greater than zero")),
value = 0;
document.body.appendChild(document.createTextNode(num));
value += num;
num--;
while (num > 0) {
document.body.appendChild(document.createTextNode(' + ' + num));
value += num;
num--;
}
document.body.appendChild(document.createTextNode(' = ' + value));

How to convert long number string value to numeric value using Javascript / jQuery

User is allowed to insert up to 25 value in textbox.
i.e. 1234567890123456789012345
On change event of textbox I need to convert that same into numeric value to perform numeric operations and then after need to display same entered value with thousand separator along with 2 decimal places.
I tried the following code:
Number($('#textbox1').val()).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",")
parseInt($('#textbox1').val(), 10).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",")
Both gives me following output
1.2,345,679,801,234,568e+21
expected output:-
1,234,567,890,123,456,789,012,345.00
Try using autoNumeric js. Find it here
something like this work for you? I found it on the internet...
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2 + '.00';
}
for the numeric point of view, still i could not get any solution at JavaScript, so I have posted the value to server side and get JSon result.
But for the display purpose I have did finally :
function ChangeAmountFormat(target) {
var $this = $(target);
var num = $this.val().replace(/,/g, '').replace(/(\s)/g, '');
var decimalPointDeleted = '';
if (lastValue.length > 0 && lastValue.indexOf('.') > 0 && num.indexOf('.') < 0) {
decimalPointDeleted = 'y';
}
if (num.indexOf('.') >= 0) {
var numSplitValues = num.split('.');
num = numSplitValues[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
num += (num.length > 0 ? ('.' + numSplitValues[1]) : '');
}
else {
if (decimalPointDeleted == 'y' && num.toString().substring((num.length - 2), num.length) == '00') {
var tempNum = num.toString().substring(0, (num.length - 2));
num = tempNum + '.' + num.toString().substring((num.length - 2), num.length);
}
else {
num = num + (num.length > 0 ? '.00' : '');
}
num = num.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
$this.val(num);
}
here, some more things also handles. Kindly ignore.

Extra + in output when looping; javascript

My desired output is: 5 + 6 + 7 + 8 + 9 + 10 = 45
The output I'm getting is: 1 + 2 + 3 + 4 + 5 + = 15 (with an extra + side on the end). I'm not sure how to get it to output without the extra + at the end, and am clearly not searching for the right terms to figure it out. Thanks!
Here's my code:
function exercise7Part2() {
// PART 2: YOUR CODE STARTS AFTER THIS LINE
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart + " + ");
loopStart++;
}
document.write(" = " + total);
}
It's because you're printing loopState + "+" which will always print the + at the end. Instead you must check if it's the last value and prevent the + from printing or else, use a ternary operator to print it.
In this example, I'm checking if both loopStart and loopMax are not equal. if they're not equal then am appending + at the end.
It will be like:
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
Here (loopStart!=loopMax ? "+" : "") is a ternary operator. The loopStart!=loopMax is an boolean expression. It's evaluated and if it's true the first parameter after ? will be used so in this case + and if its false anythign after : will be used so in this case its "" empty string.
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
loopStart++;
}
document.write(" = " + total);
With normal if condition block
while (loopStart <= loopMax)
{
total += loopStart;
if(loopStart===loopMax) {
document.write(loopStart);
} else {
document.write(loopStart+ "+");
}
loopStart++;
}
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
loopStart++;
}
document.write(" = " + total);

How do I get this script to run return the needed values of min max and sum

Here is the link to the JSFiddle
var num = prompt("Enter numbers seperated by spaces");
num = [];
var max = function (num) {
var largest = num[0];
for (var i = 1; i < num.length; i += 1) {
if (num[i] > largest) {
largest = num[i];
}
}
return largest;
};
var min = function (num) {
var smallest = num[0];
for (var i = 1; i > num.length; i -= 1) {
if (num[i] > smallest) {
smallest = num[i];
}
}
return smallest;
};
var sum = function (num) {
};
return("Minimum is " + min + ", Maximum is " + max + ", Sum is " + sum + ".");
alert(return);
I need the script to return the numerical values in the sentence that is in in return()
As was already mentioned by #JJPA you have multiple problems with your code. And you have to fix them if you want to make it working.
However if you want to learn new approaches, which could make your task easier and shorter, you may have a look at this alternative solution:
function worker(str) {
var numbers = str.split(/\s+/).map(Number),
max = Math.max.apply(this, numbers),
min = Math.min.apply(this, numbers),
sum = numbers.reduce(function(a, b) { return a + b });
return 'Minimum is ' + min + ', Maximum is ' + max + ', Sum is ' + sum + '.';
}
alert( worker(prompt()) );
It does exactly what you want but here you use all power of JavaScript array and math methods.
First, you are reading from prompt and you initialized that variable to new array. Below lines. So you don't have any values left in num.
var num = prompt("Enter numbers seperated by spaces");
num = [];
Second, you get SyntaxError: Unexpected token return because you have used return in a wrong way. Read about return by searching.
Third, you are not calling the methods min, max and sum properly.
An example code would be like below,
var num1 = prompt("Enter numbers seperated by spaces");
var num = num1.split(' ');
console.log(typeof (num));
var max = function (num) {
var largest = num[0];
for (var i = 1; i < num.length; i += 1) {
if (num[i] > largest) {
largest = num[i];
}
}
return largest;
};
var min = function (num) {
var smallest = num[0];
for (var i = 1; i > num.length; i -= 1) {
if (num[i] > smallest) {
smallest = num[i];
}
}
return smallest;
};
var sum = function (num) {
};
alert("Minimum is " + min(num) + ", Maximum is " + max(num) + ", Sum is " + sum(num) + ".");
EDIT :
replace the sum with below. Adding a return statement would solve undefined problem.
var sum = function (num) {
var s = 0;
for (var i = 0; i < num.length; i++) {
s = s + parseInt(num[i], 10);
}
return s;
};
return returns values from a function. One solution here is to take the user-input, add it as parameter when you call a function and have the result of that function return you the information you need. Here's your code rewritten to use the short-hand versions that JS allows:
var num = prompt("Enter numbers separated by spaces");
function getValues(num) {
// split the user input into an array
// and convert the string values to integers
var arr = num.split(' ').map(Number);
// Use the Math functions to get the max and min values from the array
var max = Math.max.apply(null, arr);
var min = Math.min.apply(null, arr);
// Reduce allows you to grab the sum of the values
var sum = arr.reduce(function (p, c) { return p + c; });
// return an object with all the values attached
return { max: max, min: min, sum: sum };
}
// get the result by passing in num
var result = getValues(num);
console.log(result); // { max=66, min=1, sum=79 }
console.log(result.max) // 66
console.log(result.min) // 1
console.log(result.sum) // 79
Hope it's of some use.
Demo

how can i make both the alert function and decimal function work

function check1()
{
var min = 01;
var max = 1200;
var input = document.getElementById('price');
var is_valid = (min < inputValue || max > inputValue);
}
else {
alert(inputValue + ' is not between ' + MIN + ' and ' + MAX);
return false;
The script above works well, but it is ignoring some function
how can I make both work?
You are checking for it being less than the maximum or greater than the minimum. Assuming min < max then this will always be true.
You need either an and check (for inside range) or to flip the comparisons (for outside range).
Your logic is incorrect.
is_valid will be true if inputValue is larger than min OR of it is smaller than max. Since max is larger than min, one of the two will always happen. Change your condition to:
var is_valid = min < inputValue && max > inputValue;
I think you have your is_valid condition reversed
var is_valid = (inputValue >= min && inputValue <= max);
The is_valid line should be
var is_valid = (min < inputValue && max > inputValue);
Also, MIN and MAX are not the same as min and max.
EDIT: It also seems like you want to display min and max with their decimal digits. If you need two digits, you could do something like this:
alert(inputValue + ' is not between ' + min.toFixed(2) + ' and ' + max.toFixed(2));
Mistake in Logic, change
var is_valid = (min < inputValue || max > inputValue);
as
var is_valid = (min < inputValue && max > inputValue);
For More

Categories

Resources