Trouble adding leading zeroes to submitted form data in javascript - javascript

I looked through here last night for some examples on adding leading zeroes with JavaScript and I couldn't get any of them to work for my purposes. I want to do this with the data once you hit the submit button. It is running a set of checkers when it does this and this is what I have included, but I grab the POST data in a test php page and the field I am trying to fix shows "undefined"
I need the number of digits to always be 7, regardless of whether they entered a four or five digit number. Leading zeroes need to be added. Not sure if I am kind of close or way off target with this:
function pad(number, length){
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
}
offidlength = custform.optionaldata10.value.length;
if (offidlength <7) {
custform.optionaldata10.value = pad(custform.optionaldata10.value, 7);
}

You forgot the return statement.
return str;
Should be at the end of the function.
edit function should look like:
function pad(number, length){
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}

You can make your expression simpler, if you always want 7 digits-
var offid= custform.optionaldata10.value, L= 7-offid.length;
if(L>0) custform.optionaldata10.value= '0000000'.substring(0, L)+offid;

Related

remove decimal in javascript

I want to remove decimal from number in javascript:
Something like this:
12 => 12
12.00 => 1200
12.12 => 1212
12.12.12 => error: please enter valid number.
I can not use Math.round(number). Because, it'll give me different result. How can I achieve this? Thanks.
The simplest way to handle the first three examples is:
function removeDecimal(num) {
return parseInt(num.toString().replace(".", ""), 10);
}
This assumes that the argument is a number already, in which case your second and fourth examples are impossible.
If that's not the case, you'll need to count the number of dots in the string, using something like (trick taken from this question):
(str.match(/\./g) || []).length
Combining the two and throwing, you can:
function removeDecimal(num) {
if ((num.toString().match(/\./g) || []).length > 1) throw new Error("Too many periods!");
return parseInt(num.toString().replace(".", ""), 10);
}
This will work for most numbers, but may run into rounding errors for particularly large or precise values (for example, removeDecimal("1398080348.12341234") will return 139808034812341230).
If you know the input will always be a number and you want to get really tricky, you can also do something like:
function removeDecimal(num) {
var numStr = num.toString();
if (numStr.indexOf(".") === -1) return num;
return num * Math.pow(10, numStr.length - numStr.indexOf(".") - 1);
}
You can use the replace method to remove the first period in the string, then you can check if there is another period left:
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
// invalid input
}
Demo:
function reformat(str) {
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
return "invalid input";
}
return str;
}
// show in Stackoverflow snippet
function show(str) {
document.write(str + '<br>');
}
show(reformat("12"));
show(reformat("12.00"));
show(reformat("12.12"));
show(reformat("12.12.12"));
How about number = number.replace(".", ""); ?

Devide numbers on countup function

I'm starting to learn javascript and I basically needed a countup that adds an x value to a number(which is 0) every 1 second. I adapted a few codes I found on the web and came up with this:
var d=0;
var delay=1000;
var y=750;
function countup() {
document.getElementById('burgers').firstChild.nodeValue=y+d;
d+=y;
setTimeout(function(){countup()},delay);
}
if(window.addEventListener){
window.addEventListener('load',countup,false);
}
else {
if(window.attachEvent){
window.attachEvent('onload',countup);
}
}
There's probably residual code there but it works as intended.
Now my next step was to divide the resultant string every 3 digits using a "," - basically 1050503 would become 1,050,503.
This is what I found and adapted from my research:
"number".match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(",");
I just can't find a way to incorporate this code into the other. What should I use to replace the "number" part of this code?
The answer might be obvious but I've tried everything I knew without sucess.
Thanks in advance!
To use your match statement, you need to convert your number to a String.
Let's say you have 1234567.
var a = 1234567;
a = a + ""; //converts to string
alert(a.match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(","));
If you wish, you can wrap this into a function:
function baz(a) {
a = a + "";
return a.match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(",");
}
Usage is baz(1234); and will return a string for y our.
While I do commend you for using a pattern matching algorithm, this would probably be easier to, practically speaking, implement using a basic string parsing function, as it doesn't look anywhere as intimidating from just looking at the match statement.
function foo(bar) {
charbar = (""+bar).split(""); //convert to a String
output = "";
for(x = 0; x < charbar.length; x++) { //work backwards from end of string
i = charbar.length - 1 - x; //our index
output = charbar[i] + output; //pre-pend the character to the output
if(x%3 == 2 && i > 0) { //every 3rd, we stick in a comma, except if it is not the leftmost digit
output = ',' + output;
}
}
return output;
}
Usage is basically foo(1234); which yields 1,234.

format decimal in javascript

i would like to format decimal values to specific format as like
1.23 should be shown as 0001.23 using javascript. is there any specific functions like toPrecision(), tofixed() in javascript to handle these kind of formatting or any pointers to go ahead with any solutions?
here preceeding decimal is dynamic one.
for example :
i have 2 values :
first value : 99.4545
second value : 100.32
in this second value has higher length (3)before decimal and first value has higher length after decimal(4). so subtracted result(0.8655) of this should be formatted as ###.#### (000.8685)
thank you
Just make a function that does what you want it to. Here is an example you can expand on if you want.
function pad(num, padSize){
var numString = "" + num.split('.')[0];
if(num.length < padSize){
var numZeroes = padSize-num.length;
var zeroes = "";
while(numZeroes){zeroes += "0"; numZeroes--;}
return zeroes + num;
}else return num;
}
if you want to lpad some 0 onto 1.23 you can do the following
var value = 1.23
value = ("0000000"+ value).slice(-7);
Change the -7 to be whatever you want the total string length including the decimal point to be.
Added after question edit
The above should handle your question pre-edit but for the rest of it you'll need something like this.
var formatNum = function (num, preLen, postLen) {
var value = num.split("."),
padstring = "0";
padLen = (preLen > postLen)?preLen:postLen;
for (i = 0; i < padLen; i++) {
padstring += padstring;
}
if (typeof(value[1]) === "undefined") {
value[1] = "0";
}
return ((padstring + value[0]).slice(-preLen)+ "." + (value[1] + padstring).substring(0,postLen));
}
This takes the number you want formatted and the lengths you want each string to be on either side of the '.'. It also handles the case of an integer.
If you want it to output any other cases such as returning an integer, you'll have to add that in.
Try to use a string, like "000" + some value

JQuery Phone Number Validation

I've am using jQuery validation plugin to validate a mobile phone number and am 2/3 of the way there.
The number must:
Not be blank - Done,
Be exactly 11 digits - Done,
Begin with '07' - HELP!!
The required rule pretty much took care of itself and and I managed to find the field length as a custom method that someone had shared on another site.
Here is the custom field length code. Could anyone please suggest what code to add where to also require it begin with '07'?
$.validator.addMethod("phone", function(phone_number, element) {
var digits = "0123456789";
var phoneNumberDelimiters = "()- ext.";
var validWorldPhoneChars = phoneNumberDelimiters + "+";
var minDigitsInIPhoneNumber = 11;
s=stripCharsInBag(phone_number,validWorldPhoneChars);
return this.optional(element) || isInteger(s) && s.length >= minDigitsInIPhoneNumber;
}, "* Your phone number must be 11 digits");
function isInteger(s)
{ var i;
for (i = 0; i < s.length; i++)
{
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag)
{ var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
$(document).ready(function(){
$("#form").validate();
});
The code in the question seems a very complicated way to work this out. You can check the length, the prefix and that all characters are digits with a single regex:
if (!/^07\d{9}$/.test(num)) {
// "Invalid phone number: must have exactly 11 digits and begin with "07";
}
Explanation of /^07\d{9}$/ - beginning of string followed by "07" followed by exactly 9 digits followed by end of string.
If you wanted to put it in a function:
function isValidPhoneNumber(num) {
return /^07\d{9}$/.test(num);
}
If in future you don't want to test for the prefix you can test just for numeric digits and length with:
/^\d{11}$/
You could use this function:
function checkFirstDigits(s, check){
if(s.substring(0,check.length)==check) return true;
return false;
}
s would be the string, and check would be what you are checking against (i.e. '07').
Thanks for all the answers. I've managed to come up with this using nnnnnn's regular expression. It gives the custom error message when an incorrect value is entered and has reduced 35 lines of code to 6!
$.validator.addMethod("phone", function(phone_number, element) {
return this.optional(element) || /^07\d{9}$/.test(phone_number);
}, "* Must be 11 digits and begin with 07");
$(document).ready(function(){
$("#form").validate();
});
Extra thanks to nnnnnn for the regex! :D
Use indexOf():
if (digits.indexOf('07') != 0){
// the digits string, presumably the number, didn't start with '07'
}
Reference:
indexOf().

Round the value in Javascript

I have scenario where if user enters for example 000.03, I want to show the user it as .03 instead of 000.03. How can I do this with Javascript?
You can use a regular expression:
"000.03".replace(/^0+\./, ".");
Adjust it to your liking.
This actually is trickier than it first seems. Removing leading zero's is not something that is standard Javascript. I found this elegant solution online and edited it a bit.
function removeLeadingZeros(strNumber)
{
while (strNumber.substr(0,1) == '0' && strNumber.length>1)
{
strNumber = strNumber.substr(1);
}
return strNumber;
}
userInput = "000.03";
alert(removeLeadingZeros(userInput));
How about:
function showRounded(val) {
var zero = parseInt(val.split('.')[0],10) === 0;
return zero ? val.substring(val.indexOf('.')) : val.replace(/^0+/,'') );
}
console.log(showRounded('000.03')); //=> ".03"
console.log(showRounded('900.03')); //=> "900.03"
console.log(showRounded('009.03')); //=> "9.03"
Or adjust Álvaro G. Vicario's solution to get rid of leading zero's into:
String(parseFloat("090.03")).replace(/^0+\./, ".")
This function will take any string and try to parse it as a number, then format it the way you described:
function makePretty(userInput) {
var num,
str;
num = parseFloat(userInput); // e.g. 0.03
str = userInput.toString();
if (!isNaN(num) && str.substring(0, 1) === '0') {
str = str.substring(1); // e.g. .03
} else if (isNaN(num)) {
str = userInput; // it’s not a number, so just return the input
}
return str;
}
makePretty('000.03'); // '.03'
makePretty('020.03'); // '20.03'
It you feed it something it cannot parse as a number, it will just return it back.
Update: Oh, I see If the single leading zero needs to be removed as well. Updated the code.
Assuming your input's all the same format, and you want to display the .
user = "000.03";
user = user.substring(3);
You can convert a string into a number and back into a string to format it as "0.03":
var input = "000.03";
var output = (+input).toString(); // "0.03"
To get rid of any leading zeroes (e.g. ".03"), you can do:
var input = "000.03";
var output = input.substr(input.indexOf(".")); // ".03"
However, this improperly strips "20.30" to ".30". You can combine the first two methods to get around this:
var input = "000.03";
var output = Math.abs(+input) < 1 ?
input.substr(input.indexOf(".")) :
(+"000.03").toString();

Categories