How do read the last character per string? - javascript

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)

Related

Need decimals to round to the nearest integer

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(',');
}

Seperate Digits of Positive Integer in JS using while loop without string/array

I am trying to run a program that, upon receiving a positive integer, splits it into its separate digits like so. Number is 652, output is 2, 5, 6. There is supposed to no arrays and I can't make the number a string. I've written most of the code but it's missing something that I can't figure out. The issue is really that I don't know how to store the numbers to be output during iterations. Would appreciate any help. I am using a while loop but for loop could be used as well.
function problem_09() {
var outputObj=document.getElementById("output");
var a = parseInt(prompt("Please enter a number: ", ""));
var i = 0;
var digits = ;
outputObj.innerHTML="number: "+a+"<br><br>its digits: ";
while (a>0) {
digits[i]= a%10;
a = Math.floor(a/10);
i++;
}
outputObj.innerHTML=digits;
outputObj.innerHTML=outputObj.innerHTML+"<br><br>"+"program ended";
document.getElementsByTagName("button")[0].setAttribute("disabled","true");
}
I know the issue lies with the digits and the i but I don't know how to fix it.
You could take a place value and multiply by 10 for each iteration.
function getDigits(value) {
var place = 1;
while (value >= place) {
console.log(Math.floor(value / place) % 10);
place *= 10;
}
}
getDigits(652);
getDigits(100);
A solution without using Math.floor(...)
function getDigits(n) {
var res = [];
while (n > 0) {
var r = n % 10,
d = n - r,
curr = d / 10;
n = curr;
res.push(r);
}
return res;
}
var n = prompt("Enter a number: "),
output = document.getElementById("output");
output.textContent = getDigits(+n);
<div id="output"></div>
then just to replace
var i = 0;
var digits = [];
while (a > 0) {
digits.push(a % 10);
a = Math.floor(a/10);
i++;
}
the question does not make really sense.. without arrays, but he is actually expecting the result to be an array...

Set the last number in a string to negative

I have a string with diffrent mathematical characters, and i want to make the last number negative/positive. Let's say the string is "100/5*30-60+333". The result i want is "100/5*30-60+(-333)", and i want to convert it back to positive ("100/5*30-60+333").
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n.split('+');
n.split('-');
n.split('*');
n.split('/');
console.log(n);
}
What i get is the whole hiddenText.value, and not an array of all numbers. Any tips?
First, I'd match all of the basic math operators to get their order:
const operatorsArr = n.match(/\+|\-|\/|\*/g)
Then, split the string:
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n = n.replace(/\+|\-|\/|\*/g, '|');
n = n.split('|');
console.log(n);
}
Then, you will have an array of numbers, in which you can mutate the last number easily:
n[n.lengh-1] *= -1;
Now we can combine the two arrays together:
let newArr;
for (let i = 0; i < n.length; i++) {
newArr.push(n[i]);
if (operatorsArr[i]) newArr.push(operatorsArr[i]);
}
At last, you can rejoin the array to create the new String with a seperator of your choosing. In this example I'm using a space:
newArr = newArr.join(' ')
Please let me know how that works out for you.
Let's say the string is "100/5*30-60+333". The result i want is
"100/5*30-60+(-333)", and i want to convert it back to positive
("100/5*30-60+333").
The following code does that:
let mathStr = '100/5*30-60+333';
console.log(mathStr);
let tokens = mathStr.split('+');
let index = tokens.length - 1;
let lastToken = tokens[index];
lastToken = '('.concat('-', lastToken, ')');
let newMathStr = tokens[0].concat('+', lastToken);
console.log(newMathStr); // 100/5*30-60+(-333)
console.log(mathStr); // 100/5*30-60+333
EDIT:
... and i want to convert it back to positive ("100/5*30-60+333").
One way is to declare mathStr (with the value "100/5*30-60+333") as a var at the beginning and reuse it, later as you need. Another way is to code as follows:
let str = "100/5*30-60+(-333)";
str = str.replace('(-', '').replace(')', '');
console.log(str); // 100/5*30-60+333
To get numbers You can use replace function and split check code bellow :
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = "100/5*30-60+333";
n = n.replace('+','|+');
n = n.replace('-','|-');
n = n.replace('*','|*');
n = n.replace('/','|/');
n=n.split('|');console.log(n);
// to use any caracter from array use it in removeop like example
// if we have array (split return) have 100 5 30 60 333 we get 100 for example
// we need to make removeop(n[0]) and that reutrn 100;
// ok now to replace last value to negative in string you can just make
// var lastv=n[n.length-1];
// n[n.length-1] ='(-'+n[n.length-1])+')';
//var newstring=n.join('');
//n[n.length-1]=lastv;
//var oldstring=n.join('');
}
function removeop(stringop)
{
stringop = stringop.replace('+','');
stringop = stringop.replace('-','');
stringop = stringop.replace('*','');
stringop = stringop.replace('/','');
return stringop;
}
If you really need to add "()", then you can modify accordingly
<script>
function myConversion(){
var str = "100/5*30-60-333";
var p = str.lastIndexOf("+");
if(p>-1)
{
str = str.replaceAt(p,"-");
}
else
{
var n = str.lastIndexOf("-");
if(n>-1)
str = str.replaceAt(n,"+");
}
console.log(str);
}
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
</script>

Create number range from input field

I have input field for ZIP, when user fill out field I want create two variables with first ground value.
example:
User type: 01250,
I need two variables with values 01000 and 02000
var zip = $('.js-zip-input').val();
var inputZip = zip % 1000;
var zipMax = zip - inputZip + 1000;
var zipMin = zip - inputZip;
This working for values when first char isn't 0
It's 'not working' because these are numbers, and it doesn't make sense to have a number 01000. This is really just 1000. If you really need to have the zero, you will have to turn your values into strings and add 0 to the beginning of them.
Is this what you wanted?
var zip = 1250;
var range = 1000;
var zipMin = Math.floor(zip/range) * range;
var zipMax = zipMin + range;
The code above gets the floor value of the zip input.
You can set up the range value as the difference of both outputs: in your case 1000 to 2000 would have a range of 1000. Give it a try.
As gavin pointed out, you cant have a leading 0 before the output unless you convert them to string. In this case, you can check for the length of the output (as strings) and add leading zeroes.
var outputLength = 5;
var zipMinOutput = "0".repeat(outputLength - zipMin.toString().length) + zipMin;
var zipMaxOutput = "0".repeat(outputLength - zipMax.toString().length) + zipMax;
The above code adds trailing zeroes for every missing character in the string.
(function(){
var zip = '00000140050';
var zeros = leading_zero(zip.toString().split('').map(Number)); //Number of zeros can be appended to min max values
alert(zeros);
var inputZip = zip % 1000;
var zipMax = zip - inputZip + 1000;
var zipMin = zip - inputZip;
alert(zipMax + ', ' + zipMin);
function leading_zero(x)
{
var n = 0;
for (var i = 0; i < x.length; i ++) {
if (x[i] == 0) n++;
else
break;
}
return n;
}
}());

Getting NaN error as the result

I seem to be getting a NaN error as the result in my JavaScript code.
I'm pretty new to this, would appreciate any help.
Solved by giving value to the total var.
There are a couple of problems:
You should use parseFloat instead of using strings.
You should initialize total (this is what causes the nan)
You should initialize arrays properly.
function tax() {
var price = new Array(10);
var quant = new Array(10);
var taxam = 18;
var total = 0;
for(i=0;i<10;i++) {
quant[i] = parseFloat(prompt("Insert Quantity: "));
price[i] = parseFloat(prompt("Insert Price: "));
}
for(i=0;i<10;i++) {
total += price[i] * quant[i];
}
total = total * (taxam / 100);
alert(total);
}
I guess with this var price = [10] you were trying to create an array with 10 numbers, but that is not the way it works in Javascript var price = [10] will give you an array with 10 at the 0th position. The only other tweak I would make there is make var price = [1,2,3,4,5,6,7,8,9,10] to actually achieve what you set out for initally
First of all, JavaScript is not Java ;)
You seem to try to initialize your arrays with a length of 10. This works in Java but in Javascript an array is dynamic and writing :
myArray = [10];
will just set the value 10 in the first index of the array.
Then, as you prompt the user to input numbers, the numbers will be interpreted as a string.
So it would be good to cast it to a number before working with it.
To cast it :
var value = '10000';
valueAsInt = parseFloat('10000',10);
//or simply
valueAsInt = +value;
Now we come to your problem, as total is not initialised, the first affectation will be
undefined += n;
this will give a NaN.
So just initialise total before using it :
var total = 0;
you have to initialize total variable first because it is undefined initially
var total = 0;
You have to parse the String variables to a Number:
function tax() {
var price = [10];
var quant = [10];
var taxam = 18;
var total = 0;
for(i=0;i<10;i++) {
quant[i] = Number(prompt("Insert Quantity: "));
price[i] = Number(prompt("Insert Price: "));
}
for(i=0;i<10;i++) {
total += price[i] * quant[i];
}
total = total * (taxam / 100);
alert(total);
}
tax()

Categories

Resources