i would like to know if it's possible to do this in javascript or php or anything.
i want to make an invoice number that starts with 001000, now to get the next invoice number i need to increment it by adding 1, but when i tried to do it in php. it just converts it to a number, which is not good because i need the 00 prefix. and in javascript. it just add the 1 to the end.
i know it could be done using regex but i don't know how.
EDIT: here's the invoice sequence i want to achieve.
001000
001001
001002
and when it reached to 009999 it should be 010000
please help.
SOLVED:
i used str_pad as spencer said.
php
$last_invoice = Quote::all()->last()->invoice + 1; // to convert it to number.
str_pad( ($last_invoice, 6, '0', STR_PAD_LEFT); // fill 0 prefix.
You can store the invoice number as an actual number, not a string, in order to easily increment it. When you print the number for display, pass it with leading zeros.
You can use this logic
var currentNumber = "000100";
var nextNumber = "00" + String( Number( currentNumber ) + 1 ).slice( 0 , 6 );
console.log(nextNumber);
Convert this into a function
function nextInSequence( currentNumber )
{
return "00" + String( Number( currentNumber ) + 1 ).slice( 0 , 6 );
}
var currentNumber = "000100";
currentNumber = nextInSequence( currentNumber );
console.log( currentNumber )
currentNumber = nextInSequence( currentNumber );
console.log( currentNumber )
currentNumber = nextInSequence( currentNumber );
console.log( currentNumber )
i used str_pad as #spencermay said. php
$last_invoice = Quote::all()->last()->invoice + 1; // to convert it to number.
str_pad( ($last_invoice, 6, '0', STR_PAD_LEFT); // fill 0 prefix.
Related
I'm working on some practice problems using higher- order functions and while I was able to solve this problem. I can't help but think this code is ugly and not the most eloquent it could be. Is there a way to combined map and reduce is a cleaner way than I have done ? Additionally, is there any other methods or improvements I could have used here ? I'm just looking to get better and any feedback would be appreciated.
Problem: Given a number, "sumDigits" returns the sum of all its digits.If the number is negative, the first digit should count as negative.
function sumDigits(num) {
//create array of number char
var string = num.toString().split('');
//if first char is negative symbol let the first numeric element be negative
if (string[0] === "-") {
string[1] = '-' + string[1];
string.shift();
}
//convert string to int
var toInteger = string.map(function(x) {
return Number(x);
});
//get sum
return toInteger.reduce(function(sum, current) {
sum += current;
return sum;
})
}
sumDigits(-316);
You don't need to use map at all, if you convert to number inside the reduce. Here I used the unary + operator to convert the string to a number instead of the Number constructor, but that is not better than the Number constructor, just a habit:
function sumDigits ( num ) {
const chars = num.toString( ).split( '' );
// Subtract first digit if the string starts with a '-'
// Needs to be subtracted twice, since it is included in the sum
return ( chars[0] === '-' ? -2*chars[1] : +chars[0] ) +
chars.slice( 1 ).reduce( (sum, value) => sum + +value, 0 )
;
}
I've rigged up a simple JS gallery to implement "deep linking" allowing a URL with a hash like #slide-3 to automatically load the gallery with the third slide active. There's an ad in the gallery every seventh slide. These ad slides aren't tracked so the hash becomes #slide-x followed by an image slide, i.e. #slide-7.]
I've created a helper function to convert the slide numbers from the hash into the 0-indexed slide number, taking into account these ads every seventh slide, but was curious if anyone could think of a more graceful way to calculate the proper index as my implementation looks way too complicated to my eye:
var slideNum = parseInt( window.location.hash.replace( '#slide-', '' ), 10 );
slideNum += Math.floor( ( slideNum + Math.floor( slideNum / 7 ) ) / 7 ) - 1;
return slideNum;
That works but having two floors seems like overkill. There must be a simpler way! I'm not sure of the algebraic rules that govern the floor operation however so I can't figure out how to expand/simplify myself. Any help would be appreciated.
I've included a basic JS fiddle which outputs values for the first 36 slides compared to their proper values. Feel free to change the testFunc with your solution and see if works!
var nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36];
var correct = [0,1,2,3,4,5,7,8,9,10,11,12,14,15,16,17,18,19,21,22,23,24,25,26,28,29,30,31,32,33,35,36,37,38,39,40];
var testFunc = function( n ) {
var offset = ( n + Math.floor( n / 7 ) ) / 7;
return n + Math.floor( offset ) - 1;
};
document.getElementById('text').innerHTML += 'Input Expected Output<br/>';
for( var i = 0; i < nums.length; i++ ) {
document.getElementById('text').innerHTML += nums[i] + ' ' + correct[i] + ' ' + testFunc( nums[i] ) + '<br/>';
if ( ( i + 1 ) % 6 === 0 ) {
document.getElementById('text').innerHTML += 'AD<br/>';
}
}
<div id="text"></div>
Yes, one integer division is enough:
var testFunc = function( n ) {
n = n - 1;
return Math.floor(n / 6) + n
};
Realized we have both indices on each slide element so I can simply select using the URL index and get the true slide index from the DOM. Still a fun problem to think about perhaps!?
can anybody suggest me how can i convert a given Tick format number to decimal sing JavaScript ?
Tick Format Decimal
10-8 10+8/32 == 10.25
10-16/32 10+ 16/32 == 10.50
10-8+ 10 + 8/32 + 1/64 == 10.265625
The format consists of an integer part, followed by '-' and then a fractional part specified in multiples of 1/32 (called a quote). There can be an optional '+' at the end to indicate a half-quote (1/64). As I am a beginner in JS it would be a great a help if anybody can suggest basic idea ( not full length code) to get started.
Thanks
This is how you can do this using RegExp:
Fiddle
// the tick format values
var array = ["10-8", "10-16/32", "10-8+"];
// regular expressions to check for the matches
var regexes = [/^\d+?-\d+?$/m, /^\d+?-\d+?\/\d+$/m, /^\d+?-\d+?\+$/m];
// this is where the decimal format values will go
var converted = [];
// loop through the array 'array'
for (i = 0; i < array.length; i++) {
// for each string in array loop through the array 'regexes'
for (r = 0; r < regexes.length; r++) {
// Check if any regex matches
if (regexes[r].exec(array[i])) {
// get the first digit
var x = parseInt(/^(\d+)-/m.exec(array[i])[1]);
// get the second digit
var y = parseInt(/-(\d+)\.*/m.exec(array[i])[1]);
// if the regex is last add 1 / 64 else don't
if (r == 2) {
converted.push(x + (y / 32) + (1 / 64));
} else {
converted.push(x + (y / 32));
}
}
}
}
// finally log the new array 'converted' which contains the decimal format to the console
console.log(converted)
I would do it this way:
function decTick(str) {
var toReturn = 0;
var splitted = str.split('-');
toReturn += splitted[0]*1;
if (splitted.length>1) {
if ( splitted[1].substring(splitted[1].length-1)=="+" ) {
toReturn += 1/64;
splitted[1] = splitted[1].replace('+','');
};
var fractional = splitted[1].split('/');
toReturn += fractional[0]/32;
};
return toReturn;
};
console.log( decTick('10-8') );
console.log('-----------------------------');
console.log( decTick('10-16/32') );
console.log('-----------------------------');
console.log( decTick('10-8+') );
console.log('-----------------------------');
Output:
10.25
-----------------------------
10.5
-----------------------------
10.265625
-----------------------------
This could be shortest solution, converting to equation, than calculate with eval():
function decTick(str) {
return eval( str.replace(/\-([1-9]+)$/, '-$1/32').replace('+', '+1/64').replace('-', '+').replace(/\+(\d+)\+/, '+$1/32+') );
};
console.log( decTick('10-8') );
console.log('-----------------------------');
console.log( decTick('10-16/32') );
console.log('-----------------------------');
console.log( decTick('10-8+') );
console.log('-----------------------------');
console.log( decTick('10-16/32+') );
console.log('-----------------------------');
Outputs as expected:
10.25
-----------------------------
10.5
-----------------------------
10.265625
-----------------------------
10.515625
-----------------------------
I want to calculate in Javascript but having Strange Problems.
It just adds an 1 to my String but it should calculate it. I am converting my Strings to Int with the parseInt() Function and a am calculating like this: sec = sec + 1;
var calc= parseInt($(this).find("input[name=calc]").val());
calc = calc + 1;
Your string must not be empty if don't want NaN. First check if you get an empty string:
var cal = null;
if ( $(this).find("input[name=calc]").val() ) {
cal = parseInt( $(this).find("input[name=calc]").val(), 10 );
cal++;
}
if(!!sec){
sec = parseInt(sec, 10) + 1;
alert(sec);
}
Or, in your scenario:
var fieldvalue = $(this).find("input[name=calc]").val(), calc;
if(!!fieldvalue){
calc = parseInt(fieldvalue, 10);
calc += 1;
alert(calc);
}
Do you have more code to express. It may just be coming out to 1, because sec is not set as a number
In javascript, the + operator is used for addition and concatenation of strings.
As javascript is weakly typed, you have to add information about the type. Here are two solutions:
Substract 0 from the string
sec = (sec-0) + 1;
Add unary + operator to the string
sec = (+sec) + 1;
Here's something I haven't been able to figure out for the last 30 minutes.
var file = Components.classes["#mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
file.initWithPath( sPath );
...
if ( file.fileSize < (offsetContent+bytesToRead) )
{
wt.BO.log(file.fileSize + "<" + offsetContent + "+" + bytesToRead);
bytesToRead = file.fileSize - offsetContent;
}
What the above code displays is: "577 < 50 + 50"... o.O How the hell is 577 < 100? The if statement is true...can't seem to figure why.
The plus operator (+) is used to concatenate strings, or to add up numbers in JavaScript.
Since offsetContent or bytesToRead are strings, both variables are concatenated:
"50" + "50" = "5050"
When comparing these values, the string is converted to a number, and
"5050" == 5050 -> 577 < 5050 is true, of course.
Some methods to fix the code:
// Substract bytesToRead from both sides
if ( file.fileSize - bytesToRead < offsetContent )
// Or, Turn the comparison operator, and make the right side negative
if ( file.fileSize >= -bytesToRead - offsetContent )