I have a string as an input in the form; lets say "1,5;6,10". Now, I want to compare the number at position 1 and 3 .i.e.(1 & 6). Whichever one is largest the number right to it would be printed. In this case the number 10 would be printed as 1 < 6.
Let the input is,
const customer_demand ="1,5;6,10";
I want to procced with slice() method and separate 1 and 6 with:
const number1 = customer_demand.slice(0, 1); // 1
const number2 = customer_demand.slice(4, 5); // 6
and compare the resultants with if & else. But there may be a case when the third number is two digit like:
const customer_demand ="1,5;16,10";
my slice() method index would go offset. What can I do in this regard? I hope I have made myself clear, if not please leave a comment. Thanks
In your case it's better to use split:
const customer_demand ="1,5;16,10";
const number1 = customer_demand.split(";")[0].split(",")[0]; // 1
const number2 = customer_demand.split(";")[1].split(",")[0]; // 16
Also if you want them to be Numbers don't forget to cast it using parseInt.
The solution, use split. Here's an example
const customer_demand ="1,5;16,10";
function parseNumbers(string){
return string.split(";") //returns stuff like ["1,5", "16,10"]
.map(axis=>
axis.split(",") //["1", "5"]
.map(n=>parseInt(n)) //[1,5]
)
}
//example usage
const parsedDemand=parseNumbers(customer_demand)
const [number1,number2,number3,number4]=parsedDemand
console.log(parsedDemand)
Make your life easier and break up your strings into managable arrays. Here is an example of when you don't know how many sets of numbers to compare ahead of time.
const customer_demand ="1,5;16,10";
// the following should also work for data like: "1,3,4,7;1,44;100"
let answers = [];
customer_demand.split(";").forEach( set => {
let setitems = set.split(",");
let biggest = setitems.reduce(function(a, b) {
return Math.max(Number(a), Number(b));
});
answers.push(biggest)
});
// answers is now an array - each item is the biggest number of that set. In your example it would be [5,16]
Related
My logic calculates and returns a value based on user input, I want to modify that value to always have three decimal digits
For example;
1 to 1.000
1.02 to 1.020
2.000004 to 2.000
2.5687 to 2.569
How would I achieve it on javascript?
You can use Number().toFixed() to do it
const formatVal = (val,precise = 3) =>{
return Number(val).toFixed(precise)
}
console.log(formatVal(1,3))
console.log(formatVal(1.02,3))
console.log(formatVal(2.000004,3))
console.log(formatVal(2.5687))
console.log("-----------------")
console.log(formatVal(2.5687,2))
You can do something like this,
let newNum = Number(1.34).toFixed(3);
console.log(newNum);
I am working on a project where I require to format incoming numbers in the following way:
###.###
However I noticed some results I didn't expect.
The following works in the sense that I don't get an error:
console.log(07);
// or in my case:
console.log(007);
Of course, it will not retain the '00' in the value itself, since that value is effectively 7.
The same goes for the following:
console.log(7.0);
// or in my case:
console.log(7.000);
JavaScript understands what I am doing, but in the end the actual value will be 7, which can be proven with the following:
const leadingValue = 007;
const trailingValue = 7.00;
console.log(leadingValue, trailingValue); // both are exactly 7
But what I find curious is the following: the moment I combine these two I get a syntax error:
// but not this:
console.log(007.000);
1) Can someone explain why this isn't working?
I'm trying to find a solution to store numbers/floats with the exact precision without using string.
2) Is there any way in JS/NodeJS or even TypeScript to do this without using strings?
What I currently want to do is to receive the input, scan for the format and store that as a separate property and then parse the incoming value since parseInt('007.000') does work. And when the user wants to get this value return it back to the user... in a string.. unfortunately.
1) 007.000 is a syntax error because 007 is an octal integer literal, to which you're then appending a floating point part. (Try console.log(010). This prints 8.)
2) Here's how you can achieve your formatting using Intl.NumberFormat...
var myformat = new Intl.NumberFormat('en-US', {
minimumIntegerDigits: 3,
minimumFractionDigits: 3
});
console.log(myformat.format(7)); // prints 007.000
Hi
You can use an aproach that uses string funtions .split .padStart and .padEnd
Search on MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
Here you have an example:
const x = 12.1;
function formatNumber( unformatedNumber) {
const desiredDecimalPad = 3;
const desiredNonDecimalPad = 3;
const unformatedNumberString = unformatedNumber.toString();
const unformatedNumberArr = unformatedNumberString.split('.');
const decimalStartPadded = unformatedNumberArr[0].padStart(desiredDecimalPad, '0');
const nonDecimalEndPadded = unformatedNumberArr[1].padEnd(desiredNonDecimalPad, '0');
const formatedNumberString = decimalStartPadded + '.' + nonDecimalEndPadded;
return formatedNumberString;
}
console.log(formatNumber(x))
Generate random 6 characters based on input. Like I want to turn 1028797107357892628 into j4w8p. Or 102879708974181177 into lg36k but I want it to be consistant. Like whenever I feed 1028797107357892628 in, it should always spit out j4w8p. Is this possible? (Without a database if possible.) I know how to generate random 6 characters but I dont know how to connect it with an input tbh. I would appreciate any help, thanks.
let rid = (Math.random() + 1).toString(36).substring(7);
You can create a custom hashing function a simple function to your code would be
const seed = "1028797089741811773";
function customHash(str, outLen){
//The 4 in the next regex needs to be the length of the seed divided by the desired hash lenght
const regx = new RegExp(`.{1,${Math.floor(str.length / outLen)}}`, 'g')
const splitted = str.match(regx);
let out = "";
for(const c of splitted){
let ASCII = c % 126;
if( ASCII < 33) ASCII = 33
out += String.fromCharCode(ASCII)
}
return out.slice(0, outLen)
}
const output = customHash(seed, 6)
console.log(output)
It is called hashing, hashing is not random. In your example to get rid:
let rid = (Math.random() + 1).toString(36).substring(7);
Because it is random, it's impossible to be able to produce "consistant result" as you expect.
You need algorithm to produce a "random" consistant result.
Thanks everyone, solved my issue.
Code:
let seed = Number(1028797089741811773)
let rid = seed.toString(36).substring(0,6)
console.log(rid)
Or:
let seed = Number(1028797089741811773)
let rid = seed.toString(36).substring(6)
console.log(rid)
I have an assignment to write a program that detects credit card networks, given a string of numbers. The way these are detected is by the prefix and the length. One credit card company uses 800 different sequential prefixes, and I'm wondering if there's a way to do this without writing 800 if statements. Seems like not something they'd assign.
edit: Regex is not allowed
Slice off the first 3 characters of the string, convert it to a number, and check that the number is within the range. Something like:
const verify = (str) => {
const first3 = str.slice(0, 3);
if (first3.length < 3) return false; // string is too short
const num = Number(first3);
if (Number.isNaN(num)) return false; // doesn't start with numbers
const result = num < 900 && num > 100; // check that it's between 100 and 900
console.log(result);
};
verify('92546');
verify('22546');
You could use something like that:
const startsWithSomeOf = (str, prefixes) => prefixes.some(prefix => str.startsWith(prefix));
console.log(startsWithSomeOf('123456', ['123', '111']));
console.log(startsWithSomeOf('abcdef', ['123', '111']));
Good morning, sorry for my poor English.
I'm a neophyte and I'm trying to create a javascript program that, given a string in input, if it finds inside defined substrings it returns a value to each substring and returns the sum of the values found as output. Everything ok here. But I'm finding it difficult to manage the case where in front of the substring that I'm looking for, there's for example "2x" which means that the value of the next substring (or of all subsequent substring) is to be multiplied for 2. How can I write in simple code this exception?
Example:
A1 = 1
M1 = 1
input description = A1-M1
output = 2
input descritpion = 2 x A1-M1
output = 4
Thanks in advance
For more comprehesion, you can find my code below:
let str_description = "2 x A1-M1";
var time_mont = [];
var time_cloa = [];
if(str_description.includes("A1")){
time_mont.push (0.62);
} else {
time_mont.push (0);
}
if(str_description.includes("M1")){
time_mont.push (0.6);
} else {
time_mont.push (0);
}
How can I manage "2 x " subtring?