Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have the time of day in strings ie. (830, 1450, 1630). I know I can do simple if statements to check if the length is 3 or 4 and get out (8) and (30) or (14) and (50), but is there a cleaner way to split the hour and the minute without having to check in if statements?
There's a simple way with Regular Expressions, though the syntax looks a little weird.
/^(\d{1,2})(\d{2})$/
/ / starts/stops regex definition
^ matches from the start of the string (not a random middle location)
( )( ) match two groups
\d a digit...
{1,2} that needs to exist 1 or 2 times
\d a digit...
{2} that needs to exist two times
Used in code, it would look something like this:
const times = ["830", "1520", "1015"];
const regex = /^(\d{1,2})(\d{2})$/;
const extractTime = (s) => s.match(regex).slice(1, 3);
times.map(extractTime).forEach(([hours, minutes]) => console.log({
hours,
minutes
}))
String.prototype.slice offers an easy way to do this, because negative numbers are interpreted as from the end of the string.
minutes = s.slice(-2) // last two characters of s
hours = s.slice(0, -2) // from first character up to but not including last two characters
If you know that your time will always be represented in HH:mm, you can pad the string and then slice the parts.
const parseTime = (time: string): [string, string] => {
const timePadded = time.padStart(4, 0)
return [timePadded.slice(0, 2), timePadded.slice(2, 4)]
}
parseTime("830") # ["08", "30"]
parseTime("1430") # ["14", "30"]
const a = [830, 1450, 1630];
a.forEach((item) => {
console.log('Hour = ' + ('0' + item).slice(-4).substring(0, 2) + ' Minute = ' + item.toString().slice(-2));
});
a.forEach((item) => {
console.log('Hour = ' + ('0' + item).slice(-4, -2) + ' Minute = ' + item.toString().slice(-2));
});
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to do the below
Number("0.00000000000122") results in 1.22e-12
But what I need to just that number to get converted from String to Number.
console.log(Number("0.00000000000122"))
You can do it like this:
console.log(Number("0.00000000000122").toFixed(20).replace(/\.?0+$/,""));
Explanation:
toFixed() will keep the number, and replace() will remove trailing zeroes
Edit:
It seems that you want the result of Number("0.00000000000122") to BOTH be a number and also keep it string as "0.00000000000122", not its scientific display.
In that case, you can save it as a number-type variable in ts file, then display it as a string in HTML
If you want to work with precise numbers you have to work with integers.
A Number is not an integer type, it's a float so numbers are represented in memory as a float. The toString method of the number just prints out the value in memory. The integer bit and the dot location.
const scale = 18n;
const digits = 10n ** scale;
const POUND = (number) => BigInt(number) * digits;
const toPound = (number, fraction = false) => {
if (!fraction) {
return String(number / digits);
}
const str = String(number);
if (scale < 1n) {
return str;
}
return `${str.substring(0, Number(BigInt(str.length) - scale))}.${str.substr(-Number(scale))}`;
};
const a = POUND(11000);
const b = POUND(20000);
console.log('scale', String(scale));
console.log('a', toPound(a));
console.log('b', toPound(b));
console.log('mul', toPound((a * b) / digits));
console.log('add', toPound(a + b));
console.log('div', toPound(b / (a / digits), true));
console.log('sub', toPound(b - a));
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am solving one problem .but getting correct output for small array but my solution fail when array size is large
solution
/**
* #param {number[]} digits
* #return {number[]}
*/
var plusOne = function(digits) {
let str = parseInt(digits.join(''))+1+''
return str.split('')
};
Question
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
above cases are passed
failed cases
Input
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
Output
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,0,0,0]
Expected
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]
let str = parseInt(digits.join(''))+1+''
With too many array elements, you are simply creating a number that is outside of the integer range here.
An implicit conversion to a float has to happen, and with that you get the inherent loss of precision - which then leads to several zeros in those places at the end, when you reverse the process.
Access the last array element specifically, and add 1 to the value. But if that last element had the value 9 already, you will of course have to repeat that same process for the previous one … basic application of “carry the one”.
var input = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,9];
var output = [];
// loop over input array in reverse order
for(var i=input.length-1, toadd = 1; i>-1; --i) {
// add value `toadd` to current digit
var incremented = input[i] + toadd;
if(incremented < 10) {
output.unshift(incremented); // add to front of output array
toadd = 0; // reset toadd for all following digits, if we had no overflow
}
else {
output.unshift(0); // overflow occurred, so we add 0 to front of array instead
}
}
console.log(output)
This does take an “overflow” for 9 digits at the end into account; it does not handle the case when all digits are 9 though, if you need to handle that edge case as well, please implement that yourself.
This one recursively checks the last digits:
const test1 = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
const test2 = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,9]
const plusOne = function(digits) {
if(digits[digits.length - 1] === 9){
digits = [...plusOne(digits.slice(0, -1)), 0]
}else{
digits[digits.length - 1]++
}
return digits;
};
console.log(plusOne(test1));
console.log(plusOne(test2));
You could do something like this :
var arr = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3,9,9]
function plusOne(index){
if( index < 0 ) return ; // Base case
if(arr[index] === 9){
arr[index] = 0;
plusOne(index-1); // For carry ahead
}else{
arr[index] += 1
}
}
plusOne(arr.length-1) // start with last digit
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need to replace 02:04.887004 to 02:04.887 with jquery or js.
Other times I have microseconds just with four decimals (02:04.8348) and I would have 02:04.834
I would use regexp to find $:[d][d].$ and then return it but with the three decimals
If the length of the string is reliable, you can just trim the unwanted characters from the string, e.g.
let time = '02:04.887004';
// If format is reliable, get first 9 characters
console.log(time.substr(0,9));
// If length might vary and number of decimals is at least 3
// Trim from end
console.log(time.slice(0, -(time.length - time.indexOf('.') - 4)))
// Trim from start
console.log(time.substr(0, time.length - time.indexOf('.') + 2));
If the format is more unreliable, you have more work to do.
You can use a regular expression or a split function or a substring on the string to format your timestring. Here is an example of the three:
const time = '02:04.887004';
const regex = /[\d]{2}:[\d]{2}\.[\d]{3}/
const formatTime = time => {
const match = time.match(regex);
return match ? match[0] : match;
}
const formatTime2 = time => {
const m = time.split(':').shift();
const s = time.split(':').pop().split('.').shift();
const ms = time.split('.').pop().substr(0,3);
return m + ':' + s + '.' + ms;
}
const formatTime3 = time => {
return time.substr(0,9);
}
console.log(formatTime(time));
console.log(formatTime2(time));
console.log(formatTime3(time));
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I see questions asked on truncating the leading zeros, but nothing found to solve my issue. I have a array of strings representing days returning from an api call.
Ex:
arr= ["061-094", "0561-0960", "000-005", "180+"];
arr.map(function(d){
<div>{d} days</div> // this returns 061-094 days
});
1) How can I remove the leading zeros so that it displays like:
61-94 days
561-960 days
0-5 days
2) How can display:
more than 180 days
for "180+" value?
Thanks
You can use map to generate a new array by testing each value, and if it matches the nn-nn pattern, split the string into numbers, convert to number (removes leading zeros but keeps "0" as a single value), then put them back as strings.
If the string matches the nn+ pattern, process it accordingly.
E.g.
var arr = ["061-094", "0561-0960", "000-005", "180+"];
var result = arr.map(function(v) {
// deal with nn-nn
if (/\d+-\d+/.test(v)) {
return v.split('-').map(s => +s).join('-');
}
// Deal with nn+
if (/\d+\+/.test(v)) {
return v.replace(/(\d+).*/, 'more than $1 days');
}
});
console.log(result);
If you want to wrap in HTML, then do that too.
Assuming there's no other patterns in your data than 000-000 or 180+:
arr = ["061-094", "0561-0960", "000-005", "180+", "90+"];
var result = arr.map(function(d){
if (d.substr(-1) == "+") {
return "<div>More than " + d.slice(0,-1) + " days</div>";
}
var parts = d.split("-");
var truncatedParts = [];
parts.map(function(part) {
truncatedParts.push(parseInt(part, 10));
});
return "<div>" + truncatedParts.join("-") + " days</div>" ;
});
console.log(result);
Have you tired making a String to remove all leading zeros?
String strPattern = "^0+";
This should remove all leading zeros but not trailing zeros.