miliseconds replace from 6 to 3 decimals with javascript jquery [closed] - javascript

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

Related

Create Function to get Next Number (including decimals) [closed]

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've created a function that returns the next number taking into account decimals, but am having an issue when the input number has a zero (0) proceeding the decimal.
const getNextValue = (input) => {
const newNumber = input
.toString()
.replace(/\d+$/, (number) =>
parseInt(number) +1)
return parseFloat(newNumber)
}
console.log(getNextValue(3.3)) // returns 3.4 as it should
console.log(getNextValue(3.34)) // returns 3.35 as it should
console.log(getNextValue(3.002)) // returns 3.3 as it ignores the zeros
You could skip the zeros:
const getNextValue = (input) => {
const newNumber = input
.toString()
.replace(/^\d+$|[1-9]+$/, (number) =>
parseInt(number) + 1);
return parseFloat(newNumber)
}
console.log(getNextValue(3.3)) // returns 3.4 as it should
console.log(getNextValue(3.34)) // returns 3.35 as it should
console.log(getNextValue(3.002)) // returns 3.003
console.log(getNextValue(30)) // returns 31
A completely different approach that should solve all the mentioned issues. I've added the character '1' in front of the decimal places to avoid the problem with leading zeros and to store the carry. At the end I add the carry and remove this character.
const getNextValue = (input) => {
const str = input.toString();
if (!str.includes('.')) return input + 1;
const numbers = str.split('.');
const dec = (+('1' + numbers[1]) + 1).toString();
return parseFloat(`${+numbers[0] + +dec[0] - 1}.${dec.substring(1)}`);
}
console.log(getNextValue(3.3)) // returns 3.4 as it should
console.log(getNextValue(3.34)) // returns 3.35 as it should
console.log(getNextValue(3.002)) // returns 3.003
console.log(getNextValue(3.9)) // returns 4
console.log(getNextValue(3.09)) // returns 3.1
console.log(getNextValue(30)) // returns 31

Javascript - Is there a better way to split a string based on its length? [closed]

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

Avoid Number() for scientific notation [closed]

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

Truncate zeros from string in javascript [closed]

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.

regular expression to insert * at proper places in an equation [closed]

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 7 years ago.
Improve this question
I have an expression such as xsin(x) it is valid only if * comes between x and sin(x) and make it as x*sin(x)
my idea is first search for x then insert * between x and another variable if there is a variable.
equation
sin(x)cos(x) to sin(x)*cos(x)
pow((x),(2))sin(x)to pow((x),(2))*sin(x)
sin(x)cos(x)tan(x) to sin(x)*cos(x)*tan(x)
etc
I am trying with this code..
function cal(str)
{
//var string = "3*x+56";
var regex = /([a-z]+)\(\(([a-z]+)\),\(([0-9]+)\)\)\(([a-z0-9\*\+]+)\)([\*\-%\/+]*)/;
var replacement = "$1($2($4),($3))$5";
while(str.match(regex))
{
str = str.replace(regex,replacement);
}
return str;
}
This one matches right parentheses followed by a letter (e.g. )s ), and inserts a * (e.g. )*s )
It also replaces x followed by a letter with x* and that letter
It should work for x+sin(x) and xsin(x)
function addStars(str) {
return str.replace(/(\))([A-Za-z])/g,function(str, gr1, gr2) { return gr1 + "*" + gr2 }).replace(/x([A-Za-wy-z])/g,function(str, gr1) { return "x*" + gr1 })
}
document.write(addStars("x+sin(x)tan(x)ln(x)+xsin(x)"))
Help from:
JavaScript - string regex backreferences
qwertymk's answer
> 'sin(x)cos(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "sin(x)*cos(x)"
> 'pow((x),(2))sin(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "pow((x),(2))*sin(x)"
> 'sin(x)cos(x)tan(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "sin(x)*cos(x)*tan(x)"
This says: replace anything that doesn't start at the beginning and has three letters with a * and everything that matched

Categories