How to Validate Time in decimal using javascript? - javascript

User input time in the decimal format.
like
0.00 //Incorrect
1.54 //Correct value
1.60 //Incorrect value
1.59 //correct value
I have tried to make a regular expression function but it is showing incorrect for all values
var regex = /^[0-9]\d*(((,?:[1-5]\d{3}){1})?(\.?:[0-9]\d{0,2})?)$/;
if (args.Value != null || args.Value != "") {
if (regex.test(args.Value)) {
//Input is valid, check the number of decimal places
var twoDecimalPlaces = /\.\?:[1-5]\d{2}$/g;
var oneDecimalPlace = /\.\?:[0-9]\d{1}$/g;
var noDecimalPlacesWithDecimal = /\.\d{0}$/g;
if (args.Value.match(twoDecimalPlaces)) {
//all good, return as is
args.IsValid = true;
return;
}
if (args.Value.match(noDecimalPlacesWithDecimal)) {
//add two decimal places
args.Value = args.Value + '00';
args.IsValid = true;
return;
}
if (args.Value.match(oneDecimalPlace)) {
//ad one decimal place
args.Value = args.Value + '0';
args.IsValid = true;
return;
}
//else there is no decimal places and no decimal
args.Value = args.Value + ".00";
args.IsValid = true;
return;
} else
args.IsValid = false;
} else
args.IsValid = false;

It's probably easier to do working with a number:
var time = (+args.Value).toFixed(2); // convert to float with 2 decimal places
if (time === args.Value) {
// it's a valid number format
if (time !== 0.0 && time < 24) {
// the hours are valid
if (time % 1 < 0.6) {
// the minutes are valid
}
}
}
You can collapse all that up into a nice one-liner:
if (time === args.Value && time !== 0.0 && time < 24 && time % 1 < 0.6) {
}
and even a boolean/ternary
var valid = time === args.Value && time !== 0.0 && time < 24 && time % 1 < 0.6;
alert( time === args.Value && time !== 0.0 && time < 24 && time % 1 < 0.6 ? 'valid' : 'invalid' );

Related

Error when trying to convert binary to decimal (no output)

I am trying to write a function that must convert a decimal number to binary and vice versa.
The function receives two arguments:
number, either binary/decimal
conversion to perform
Works fine when I pass binaryDecimal(5, 2); (// prints 101) for decimal to binary conversation.
When I pass the arguments to the function to convert binary to decimal, it does not print anything.
const binarioDecimal = (number = 0, base = 0) => { // 0 by default if the user does not pass any value
if (number === 0 || base === 0) {
console.log(0);
} else if (typeof number === "number" && typeof base === "number") {
if (base === 2) {
let num = number;
let binary = (num % 2).toString();
for (; num > 1; ) {
num = parseInt(num / 2);
binary = (num % 2) + binary;
}
console.log(binary);
}
} else if (typeof number === "number" && typeof base === "number") {
//this is where i think the function fails
if (base === 10) {
var decimal = 0,
i = 0,
resto;
while (number !== 0) {
resto = number % 10;
number = Number.parseInt(number / 10);
decimal = decimal + resto * Math.pow(2, i);
++i;
}
console.log(decimal);
}
}
};
binarioDecimal(); // 0
binarioDecimal(23, 2); // 10111
binarioDecimal(101, 10); //does not print anything :(
What if you split the checks into two separate conditions?
const binarioDecimal = (number = 0, base = 0) => {
if (number === 0 || base === 0) {
console.log(0);
}
if (base === 2) {
var num = number;
var binary = (num % 2).toString();
for (; num > 1; ) {
num = parseInt(num / 2);
binary = (num % 2) + binary;
}
console.log(binary);
}
if (base === 10) {
var decimal = 0,
i = 0,
resto;
while (number !== 0) {
resto = number % 10;
number = Number.parseInt(number / 10);
decimal = decimal + resto * Math.pow(2, i);
++i;
}
console.log(decimal);
}
}
binarioDecimal(); // 0
binarioDecimal(23, 2); // 10111
binarioDecimal(101, 10); // 5
The second
else if (typeof number === "number" && typeof base === "number")
is never executed.
Maybe try something like:
else if (typeof number === "number" && typeof base === "number" && base === 2)
{
...
}
else if (typeof number === "number" && typeof base === "number" && base === 10)
{
...
}
if you see what I mean!
The problem appears to be in your outermost if() statement. You have the following:
if(number === 0 || base === 0) {
/* your code */
} else if(typeof number === "number" && typeof base === "number") {
if(base === 2) { /* your code */ }
} else if(typeof number === "number" && typeof base === "number") {
if(base === 10) { /* your code */ }
}
Using this, if you call binarioDecimal(101, 10);:
if(number === 0 || base === 0)
is false
else if(typeof number === "number" && typeof base === "number")
is true
then if(base === 2)
is false
It then exits the whole statement, assuming it has fulfilled its purpose, never reaching the third else if(...) because it's the same as the previous one.
Putting the if(base === 10) with the if(base === 2) statement should resolve the issue.
if(number === 0 || base === 0) {
/* your code */
} else if(typeof number === "number" && typeof base === "number") {
if(base === 2) {
/* your code */
} else if(base === 10) {
/* your code */
}
}
That should solve why your code is never reached when the base is 10. Alternatively, outside of doing so for a coding exercise, you may want to look at Number.prototype.toString(radix); and Number.parseInt(string, radix); to convert between number bases. Hopefully this information is useful!

Auto slash(/) for date input using Javascript MM/YY

I'm working on an input form that includes a credit card expiration date for only Visa and Mastercard. These two restrict the expiration date to MM/YY. I'm using the following script elsewhere on the form to automatically introduce slashes as the user types in their birth date:
$(function() {
var date = document.getElementById('ccexp');
function checkValue(str, max) {
if (str.charAt(0) !== '0' || str == '00') {
var num = parseInt(str);
if (isNaN(num) || num <= 0 || num > max) num = 1;
str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString();
}
return str;
}
date.addEventListener('keydown', function(e) {
this.type = 'text';
var input = this.value;
var key = e.keyCode || e.charCode;
if (key == 8 || key == 46) // checks if backspace or delete is being pressed
return false;
if (/\D\/$/.test(input)) input = input.substr(0, input.length - 1);
var values = input.split('/').map(function(v) {
return v.replace(/\D/g, '')
});
if (values[0]) values[0] = checkValue(values[0], 12); // validates month 1-12
if (values[1]) values[1] = checkValue(values[1], 31); // validates day 1-31
var output = values.map(function(v, i) {
return v.length == 2 && i < 2 ? v + '/' : v;
});
this.value = output.join('').substr(0, 10);
});
});
(The requirements on this project are for users to type in dates, rather than use a date picker). I'd like to use a version of this script to look for MM/YY, but I really don't know how to parse this well enough myself.

Javascript Function to Format as Money [duplicate]

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 6 years ago.
I have a script where I pass it a string, and it'll return that string formatted as dollars. So if I send it "10000" it'll return "$10,000.00" Now the problem is that when I send it "1000000" ($1 million) it returns "$1,000.00" because it's only setup to parse based on one set of zeros. Here's my script, how can I adjust it to account for two sets of zeros ($1 million) ??
String.prototype.formatMoney = function(places, symbol, thousand, decimal) {
if((this).match(/^\$/) && (this).indexOf(',') != -1 && (this).indexOf('.') != -1) {
return this;
}
places = !isNaN(places = Math.abs(places)) ? places : 2;
symbol = symbol !== undefined ? symbol : "$";
thousand = thousand || ",";
decimal = decimal || ".";
var number = Number(((this).replace('$','')).replace(',','')),
negative = number < 0 ? "-" : "",
i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return negative + symbol + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : ""); };
Thanks in advance for any useful information!
function formatMoney(number) {
return number.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
}
console.log(formatMoney(10000)); // $10,000.00
console.log(formatMoney(1000000)); // $1,000,000.00
Give this a shot it looks for a decimal separator but you can remove that part if youd like:
{
number = parseFloat(number);
//if number is any one of the following then set it to 0 and return
if (isNaN(number)) {
return ('0' + '{!decimalSeparator}' + '00');
}
number = Math.round(number * 100) / 100; //number rounded to 2 decimal places
var numberString = number.toString();
numberString = numberString.replace('.', '{!decimalSeparator}');
var loc = numberString.lastIndexOf('{!decimalSeparator}'); //getting position of decimal seperator
if (loc != -1 && numberString.length - 2 == loc) {
//Adding one 0 to number if it has only one digit after decimal
numberString += '0';
} else if (loc == -1 || loc == 0) {
//Adding a decimal seperator and two 00 if the number does not have a decimal separator
numberString += '{!decimalSeparator}' + '00';
}
loc = numberString.lastIndexOf('{!decimalSeparator}'); //getting position of decimal seperator id it is changed after adding 0
var newNum = numberString.substr(loc, 3);
// Logic to add thousands seperator after every 3 digits
var count = 0;
for (var i = loc - 1; i >= 0; i--) {
if (count != 0 && count % 3 == 0) {
newNum = numberString.substr(i, 1) + '{!thousandSeparator}' + newNum;
} else {
newNum = numberString.substr(i, 1) + newNum;
}
count++;
}
// return newNum if youd like
};

Converting string to number of seconds

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();

parseFloat.toPreceision just adds zeros

I'm sending the number/string 0.001 to a the function below:
SignificantFigures = 4;
function LimitNumberOfDigits(num) {
var tempStr = "";
if (isNaN(num))
return "\xD8";
else{
if (parseFloat(num) === 0 || (num.toString().indexOf('.') === -1 && parseInt(num) < 9999) || num.toString().length <= 4) {
return num;
}
tempStr = parseFloat(num).toPrecision(SignificantFigures);
if (tempStr.indexOf("e") > -1) {
var startE = tempStr.indexOf("e");
var endE = 0;
for (var i = startE +2 ; i < tempStr.length; i++ ) { // + to ignore e and sign (+ or - )
if(parseInt(tempStr[i], 10) > 0) {
endE = i;
}else {
break;
}
}
if (startE + 2 === endE) {
var pow = tempStr[endE];
} else {
var pow = tempStr.substring(startE +2 ,endE);
}
return tempStr.substring(0,startE) + "*10<sup>"+ pow +"</sup>";
}else {
return parseFloat(num).toPrecision(SignificantFigures);
}
}
}
When im sending 0.2 or even 0.11 im getting like 0.2000 and 0.1100.
The issue here is the toPrecision acts like ToFixed.
Ideas?
EDIT
What i want? simple as that, if a numbers needs to be changed e.g 0.012312312041 it should be 0.0123 , numbers like 0.12 or 28 should stay the same.

Categories