Convert comma's into periods js - javascript

So I'm trying to make a calculation but it obviously wont calculate with ',' in the numbers. I want to change these vars and make the ',' into '.' using javascript
oldSum.value = '48,35'
newSum.innerHTML = '€43,40'
var oldSumPre = oldSum.value;
var oldStripped = oldSumPre.replace(/,/g, ".");
var newSumPre = newSum.innerHTML;
var newStripped = newSumPre.replace(/,/g, ".");
bedrag.innerHTML = oldStripped - newStripped;
Is what Im doing right now.. but it changes bedrag.innerHTML into NaN

var str = "R,e,p,l,a,c,e";
var res = str.replace(/,/g, ".");
alert (res);

Suppose your variable is vNum. You need to replace all commas with '.' using this
vNum = vNum.replace(",", ".");

In general you could use a localization / internationalization library, which will solve some other tasks you are likely to run into as well.
For example this one:
https://github.com/jquery/globalize/blob/master/doc/api/number/parse-number.md
Snippet:
Globalize.locale( "es" );
Globalize.parseDate( "3,14" ); // 3.14

Related

Line-breaks in between of text using JS ,(Dynamically)

I am stuck on a very beginner problem in JS, what I'm trying to do is add line-breaks in between text which the script adds dynamically after generating a random string, but I could not find a source that would match my case
The code that picks a random string
var textArray = [
'Gateway to wild imaginations!',
'Activating the send portal :D',
'Empowering nothing ;P'
];
var randomNumber = Math.floor(Math.random()*textArray.length);
var rndStr = textArray[randomNumber];
const h_1_elem = document.getElementById('main-h1');
h_1_elem.innerText = rndStr;
I would consider myself a beginner in programming so take this question with a pinch of salt
You could use \n to insert a new line since you are using
h_1_elem.innerText = rndStr + "\n";
Also I created a function called randomNumber in order to call it more than one time.
var textArray = [
'Gateway to wild imaginations!',
'Activating the send portal :D',
'Empowering nothing ;P'
];
const h_1_elem = document.getElementById('main-h1');
h_1_elem.innerText = textArray[randomNumber()] + "\n";
h_1_elem.innerText += textArray[randomNumber()] + "\n";
function randomNumber() {
let number = Math.floor(Math.random()*textArray.length);
return number;
}
<div id="main-h1"></div>
If you run the code multiple times, you will get different messages. Just keep adding more :)
Regards
============ EDITED ============
Oh, you want a break line after each word. Didn't understand the question that way. So, for that you should use something like this:
var textArray = [
'Gateway to wild imaginations!',
'Activating the send portal :D',
'Empowering nothing ;P'
];
const h_1_elem = document.getElementById('main-h1');
h_1_elem.innerText = textArray[randomNumber()].replaceAll(" ","\n");
function randomNumber() {
let number = Math.floor(Math.random()*textArray.length);
return number;
}
<div id="main-h1"></div>
I just used
replaceAll(" ", "\n")
In order to replace every space by a break line. Hope this is what you want.
Regards
Don't use .innerText and instead use .innerHTML along with the HTML line break element of <br>:
var textArray = [
'Gateway to wild imaginations!',
'Activating the send portal :D',
'Empowering nothing ;P'
];
var rndStr = textArray[Math.floor(Math.random()*textArray.length)];
const h_1_elem = document.getElementById('main-h1');
h_1_elem.innerHTML = rndStr + "<br>";
rndStr = textArray[Math.floor(Math.random()*textArray.length)];
h_1_elem.innerHTML += rndStr + "<br>";
<div id="main-h1"></div>

Javascript extract last numbers from Math.random

So I'm trying to do a script for Photoshop with javascript and I can't get the last 6 number from a Math.random.
I tried using the same code as in Strings with "randomID.substr(randomID.length - 6);" or "randomID.substr(-6);" but that didn't work.
var kodi = 'FJ0B';
var randomID = Math.floor(Math.random() * (999999999999 - 100000000000 + 1) + 100000000000);
var lastSix = randomID.toFixed(-6);
var kontrataLayer = (kodi.charAt(0) + lastSix);
Math.floor works fine, I need it with 12 digits for another function.
Thank you.
What about:
var randomIDString = randomID.toString();
var lastSix = Number(randomIDString.substr(randomIDString.length - 6));
For substr to work you need to convert the number to a string. Maybe that's why it didn't work for you earlier?

Calculating 2 values from fields but it's not working properly

I am calculating 2 fields on a form with values but it seems in some cases it's not working. Here's my javascript. I am adding $oneTimeCostField and $recurringTotalCostField to get the value into the $totalRetailAmountField. Here's the result I am getting when I add say 1,555.00 + 566.00 = the value is 567.00 (?). Any idea what I'm doing wrong? In some cases it works correctly when the values are lower. Thanks, just stumped
var $recurringCostField = $('#am_attribute_campaign_addon_monthly_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_oie_string_total_monthly_cost_value');
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseFloat(num1) + parseFloat(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val(result.toFixed(2));
}
}
calcVal();
$oneTimeCostField.on("keydown keyup", function() {
calcVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcVal();
});
You need to remove the commas before parsing:
var result = parseFloat(num1.replace(/,/g, '')) + parseFloat(num2.replace(/,/g, ''));
similiar question on this link
Remove commas from the string using JavaScript
That is because parseFloat() converts the string "1,555.00" to the number 1.
To convert it to a proper floating point number, it needs to include a single dot only.
console.log(parseFloat("1.555"));

Subtract two strings in jS

I want to find the difference between two strings in Javascript.
Given two strings
var a = "<div>hello</div><div>hi</div><div>bye/</div>";
var b = "<div>hello</div><div>hi</div>";
The result should be "<div>bye</div>".
Like in formula:
var result = a - b;
& I need this implementation in Javascript (Is there any default method is available for this in JS??)
Can anyone help me out?
You can obtain the desired output with
var s = a.replace(b, '')
This seems like an x/y question. But in any case, I’ll try to help you out.
We want to find the location of b within a.
var start = a.indexOf(b);
var end = start + b.length;
Now put it together.
return a.substring(0, start - 1) + a.substring(end);
var a = "<div>hello</div><div>hi</div><div>bye/</div>";
var b = "<div>hello</div><div>hi</div>";
c = a.substring(b.length)
console.log(c);

Adding User input without rounding (Google Apps Script)

I am adding a users input in to UI as they add numbers and returning the results. The input is currency so I need to carry it out two decimals and not round.
Here is an example of my code:
function ceiling2(number) {
var ceiling2;
return ceiling2 = Math.ceil(number*100)/100;
}
//Totals
function lD23Total (e){
var app = UiApp.getActiveApplication();
var tB1v = parseInt(e.parameter.TextBox1);
var tB9v = parseInt(e.parameter.TextBox9);
var tB17v = parseInt(e.parameter.TextBox17);
var tB25v = parseInt(e.parameter.TextBox25);
var tB33v = parseInt(e.parameter.TextBox33);
var tB41v = parseInt(e.parameter.TextBox41);
var tB49v = parseInt(e.parameter.TextBox49);
var lD23 = app.getElementById("LabelD23").setStyleAttribute('fontWeight','bold');
var lD23T = tB1v + tB9v + tB17v + tB25v + tB33v + tB41v + tB49v;
lD23.setText("$ " + ceiling2(lD23T));
var app = UiApp.getActiveApplication();
app.close();
return app;
}
Currently it returns a rounded number.
I appreciate an suggestions you may offer!
Jon
The function parseInt() will convert the value to an integer, dropping the values after the decimal. Use parseFloat() instead.
I think your function is just fine...
if you remove the parseInt() and replace it either with parseFloat()as suggested by Eric or by Number() it should work...
if not then the problem might come from the way numbers are written:
If you used 26,4567 but you should use 26.4567 with a dot as separator in place of a comma.
Could you try and keep us informed ?
regards,
Serge
Or you can use this before sending to your function:
var newnumber=Number(number.toString().replace(",","."));// convert to string, replace comma with dot and set as number again.
and your function will work in both cases

Categories

Resources