Need decimals to round to the nearest integer - javascript

I'm using the price adjuster script, but after I run the script I need it to also round to the nearest integer with the following logic: If the fractional part is .25 and higher, round up, and otherwise round down.
Examples:
$1,316.10 to become $1,316.00
$1,126.28 to become $1,127.00
Is there a way to also only affect a certain character style as well?

Try this:
var style_name = 'my_style';
// find all the prices
app.findGrepPreferences = NothingEnum.nothing;
app.findGrepPreferences.findWhat = "\\$[\\d,]+\\.\\d+";
var prices = app.activeDocument.findGrep();
if (prices.length == 0) { alert('Nothing was found'); exit() }
// loop through all the finds
var i = prices.length;
while(i--) {
// skip if the price has another style name
if (prices[i].appliedCharacterStyle.name != style_name) continue;
// get the numbers
var numbers = prices[i].contents.slice(1).replace(/,/g,'').split('.')
var number_left = numbers[0];
var number_right = numbers[1];
// change the numbers
if (number_right >= 25) number_left++;
var rounded_number = '$' + add_commas(number_left) + '.00';
// replace the price with the rounded number
prices[i].contents = rounded_number;
}
// function to convert: 12345678 --> "12,345,678"
function add_commas(num) {
var arr = num.toString().split('');
var new_arr = [];
while (arr.length) {
new_arr.unshift([arr.pop(),arr.pop(),arr.pop()].reverse().join(''));
}
return new_arr.join(',');
}

Related

How to convert a long string (more than 16 digits) into numbers

this is a function just increment one number into array
but the problem i interface when i put alot of numbers into array (more than 16 digits)
when i use parseInt() just returned 16 correct numbers and more than that be zero
6145390195186705000
and expected
6145390195186705543
the function
var plusOne = function(digits) {
var numbersInString = digits.join('');
var theNumbers = parseInt(numbersInString);
var theNumbersPlusOne = theNumbers + 1;
var result = String(theNumbersPlusOne).split("").map((theNumbersPlusOne) => {
return Number(theNumbersPlusOne);
});
return result;
};
console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));
Just expanding on my above comment with another solution...
You've exceeded the maximum safe integer value. (Number.MAX_SAFE_INTEGER, which equals 9007199254740991). Numbers larger than this are not supported with standard integer types in javascript, or rather there's not enough precision to represent them. Anything larger than this is represented in scientific notation and the extra digits are truncated and represented only as zeroes.
With that said, you don't even need to convert the array to a string to an integer just to increment it. You can just increment the individual digits in the array, starting at the end and working your way forwards to "carry the 1" so to speak.
var plusOne = function(digits) {
for(let i = digits.length - 1; i > -1; i--)
{
if(digits[i] == 9)
{
digits[i] = 0;
if(i == 0)
digits = [1].concat(digits);
}
else
{
digits[i]++;
break;
}
}
return digits;
};
console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));
You can use BigInt to handle this problem.
var plusOne = function(digits) {
var numbersInString = digits.join('');
var theNumbers = BigInt(numbersInString);
var theNumbersPlusOne = theNumbers + BigInt(1);
var result = theNumbersPlusOne.toString().split("").map((theNumbersPlusOne) => {
return Number(theNumbersPlusOne);
});
return result;
};
console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));

How do I divide numbers from two arrays into a new one. I am trying to make a rational zeroes thereom calculator of sorts for fun

This is as far as I've gotten. I have factored the numbers successfully, but I just need to distribute and divide them into the pOverQ array.
var p = readInt("What is your p: ");
var q = readInt("What is your q: ");
var factorP = [];
var factorQ = [];
var pOverQ = [];
var num = 0;
function start(){
factor(p, q);
println(factorP);
println(factorQ);
p_Q(p, q);
println(pOverQ);
}
function factor(p ,q){
for(var i = 1; i <= p; i++) {
if(p % i == 0){
factorP.push(i);
}
if(q % i == 0){
factorQ.push(i);
}
}
}
function p_Q(p, q){
for(var i = 0; i < (factorP.length)*2; i++){
pOverQ.push(factorP[i]/factorQ[i]);
}
}
I hope you can help!!!
It looks like you are trying to build something like this:
rational zeros theorem calculator
Here are a few steps towards it:
function factor(p){ // find all factors of a single number
let res=[];
for(let i=1;i<=p;i++) if(p%i == 0) res.push(i);
return res;
}
function p_q(P,Q){ // combine P- and Q-arrays and find all distinct fractions
const coll={}, qarr=factor(Q);
factor(P).forEach(p=>qarr.forEach(q=>{
let frac=reduce(p,q);
coll[frac.join("/")]=frac
}));
return coll;
}
// https://stackoverflow.com/a/4652513/2610061
function reduce(num,den){ // reduce a given fraction
// greatest common denominator:
function gcd(a,b){return b ? gcd(b, a%b) : a;};
const g = gcd(num,den);
return [num/g, den/g];
}
const res=p_q(6,7);
console.log(Object.keys(res)); // show the fractions as text ...
console.log(Object.values(res).map(([n,d])=>n/d)); // ... and as values
As #jsN00b already mentioned, you will need to consider both, positive and negative values of the calculated fractions as possible solutions for your polynomium. But I 'll leave that bit to you.

How do read the last character per string?

My code generates a string, as shown in the image. At the end of each line a number in euros is shown, let call these euros1 and euros2. The idea is that the amount ✓ icons is multiplied with euros1 and euros2 shown per line. So in the case of my example: (10,45 + 5,50) x 2 = 31,90 for the first line, and for the second line (18,24 + 9,60) x 3 = 83,52. These numbers are supposed to be combined to a total of 115,42.
However my current code produces a total of 218,95. So it takes the sum of all the euros1 and euros2 and multiplies it by the total amount of ✓ icons.
How can I calculate the sum of the euros1 + euros2 x the amount ✓ icons, per line?
I think a for loop could help me, however I am new to Javascript and I am not sure how to proceed.
var temp = g_form.getValue('mwadm_onkosten_list_refList_changes');
var count = (temp.match(/✓/g) || []).length;
var lastChar = temp[temp.length -1];
if (count != temp);
{
total = total * count;
}
I was thinking of a split solution just like #dganenco mentioned. I created a TEMP variable to reproduce your result string. And execute a function on it foreach row.
And i intentionally kept it really simple. Hope this helps.
var temp = ["✓|| €10,45 | €1,50 ", "✓|| €10,45 | €2,50 ", "✓|| €10,45 | €3,50 "];
var totalTimes = (String(temp).match(/✓/g) || []).length;
//perform function for each row
temp.forEach(CalculateRow);
//Splits the row, Gets euro1 as decimal, euro2 as decimal, calculates the amount a character is found, calculates total, prints it to console.
function CalculateRow(item, index) {
var arr = item.split('|');
var euro1 = GetValueFromArray(arr,1);
var euro2 = GetValueFromArray(arr, 2);
var times = (String(arr).match(/✓/g) || []).length;
var _total = (euro1 + euro2) * times;
console.log(_total);
}
//Takes the index value, and casts it to decimal value
function GetValueFromArray(arr, index){
var getindex = arr.length -index;
var result = arr[getindex];
result = result.replace('€', '');
return parseFloat(result, 10);
}
I've got a solution for you in case if is it possible to only split strings by | symbol, then get last 2 values and do all needed stuff using them.
const strArr = ['asd|addf|$56.60|$10.40', 'asd|addf|$5.60|$1.40'];
let sum = 0;
strArr.forEach(str => {
const splitted = str.split('|');
debugger;
const x = getNumber(splitted[splitted.length - 2]);
const y = getNumber(splitted[splitted.length - 1]);
sum += (x+y)*2;
});
function getNumber(str){
return +str.substring(1);
}
console.log(sum)
Assuming temp is the multiline string in the form of
asd|√|√| €12.34 | €15.25
zxc|√|| €18.34 | €19.25
This code should give you a sum of last two numbers multiplied by the amount of √
var temp = "asd|√|√| €12.34 | €15.25\nzxc|√|| €18.34 | €19.25"
let lines = temp.split('\n')
let linesSummaries = []
for(let line of lines){
var count = line.match(/√/g).length
var vars = line.split('|')
var x = parseFloat(vars[vars.length-1].match(/\d+\.?\d*/))
var y = parseFloat(vars[vars.length-2].match(/\d+\.?\d*/))
var lineSum = (x + y ) * count
linesSummaries.push(lineSum)
}
console.log(linesSummaries)

Generate string of random number that includes some number and exclude some number

I have a problem about generating string in javascript.
I have an array of number that string should contains atleast 1, and 1 number(up to 7 digits) that must not contains in a string. String length must be 7.
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ... //input from user
I tried to generate it by random select from array, random position and random other number around selected number. Then check if string contains excluded number, generate it again.
//random select number
var getRandom = incNumber[Math.floor(Math.random() * incNumber.length)];
//random position of number
var position = Math.floor(Math.random() * 6);
//length of other string after selected number
var afterlen = 7 - (position+2);
//genNum(...) is my function that use to generate string of number in specific length.
var nstr = genNum(position)+getRandom+genNum(afterlen);
while (nstr.includes(exclude)) {
nstr = genNum(position)+getRandom+genNum(afterlen);
}
but doing this take too long time or sometimes freeze my browser. How should I fix it.?
edited: It's my homework about phonenumber.
final string should be like "37915002"
Edited my code again
Does that now match your needs? It has got pretty messy and I'm not sure if it's correct (I'm never sure.. xD) hope you can get some inspiration though.
// Variables
var initialList = ["100", "5", "19", "88", "10", "90"];
var excludeList = ["9", "10"];
var resultLength = 7;
var finalString = "";
// Create a third final array that is filtered
var finalList = initialList.filter(element => {
let shouldBeIncluded = true;
excludeList.forEach(excluder => {
Array.from(excluder).forEach(excluderFragment => {
if (element.includes(excluderFragment)) shouldBeIncluded = false;
});
});
if (shouldBeIncluded) return true;
});
// Check if all were excluded
if (finalList.length == 0) {
// Do error handling here
} else {
// Create the list
for (let i = 0; i < resultLength; i++) {
finalString += finalList[Math.floor(Math.random() * finalList.length)];
}
// Shorten the list because multiple digits values
finalString = finalString.slice(0, 7);
console.log(finalString);
}
You could start by filtering the unwanted number from the incNumber and doing everything the same way but on the new array
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = "12";
var filteredNumbber =incNumber.filter(number=> number!==exclude);
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
if we assume exclude is not a value but instead an array of values you would change the formula to
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ["15"];
var filteredNumbber =incNumber.filter(number=> !exclude.includes(number));
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
as some people suggested random variable may end up as undefined if we exclude all the numbers inside of incNumber, if that was the case we should add an additional check in case that happens
if (random!==undefined) var nstr = genNum(position)+random+genNum(afterlen);

JavaScript random password with specific format

I would like to generate a random password respecting the following format:
at least one uppercase character
at least one lowercase character
at least one digit
the length should be at least 6 characters
I thought about it and the only thing I could think of is some function that is quite long and ugly. Could you guys offer me a simpler, more efficient way of doing this?
PS: I'm using this function not on the client side, but on the server side, on my Node.js web application.
Here is my solution:
/**
* sets of charachters
*/
var upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
var lower = 'abcdefghijklmnopqrstuvwxyz'
var digit = '0123456789'
var all = upper + lower + digit
/**
* generate random integer not greater than `max`
*/
function rand (max) {
return Math.floor(Math.random() * max)
}
/**
* generate random character of the given `set`
*/
function random (set) {
return set[rand(set.length - 1)]
}
/**
* generate an array with the given `length`
* of characters of the given `set`
*/
function generate (length, set) {
var result = []
while (length--) result.push(random(set))
return result
}
/**
* shuffle an array randomly
*/
function shuffle (arr) {
var result = []
while (arr.length) {
result = result.concat(arr.splice(rand[arr.length - 1]))
}
return result
}
/**
* do the job
*/
function password (length) {
var result = [] // we need to ensure we have some characters
result = result.concat(generate(1, upper)) // 1 upper case
result = result.concat(generate(1, lower)) // 1 lower case
result = result.concat(generate(1, digit)) // 1 digit
result = result.concat(generate(length - 3, all)) // remaining - whatever
return shuffle(result).join('') // shuffle and make a string
}
console.log(password(6))
How about we place the formats into strings and we can place than into an array, then randomly chose one and randomly chose and item in that sub-array item:
var uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lowers = "abcdefghijklmnopqrstuvwxyz";
var digits = "01234567890";
var all = uppers + lowers + digits;
var choices = [uppers,lowers,digits];
var checks = [];
var password = "";
var ranLength = Math.ceil(Math.random()*10)+3;
for(var i=0; i<ranLength; i++){
var choice = choices[Math.ceil(Math.random()*3)-1];
var choiceItem = choice[Math.ceil(Math.random()*(choice.length))-1]
password += choiceItem;
}
for(var i=0; i<3; i++){ // Append needed values to end
var choice = choices[i];
var choiceItem = choice[Math.ceil(Math.random()*(choice.length))-1]
password += choiceItem;
}
password = password.split('').sort(function(){
return 0.5 - Math.random();
}).join('');
alert(password);
Edited: Sorry made a small mistake. Fixed.
Try this...
var randomstring = Math.random().toString(36).slice(-8);

Categories

Resources