I have a WooCommerce store, which is connected with Zapier to a Google spreadsheet. In this file, I keep track of the sales etc. Some of these columns contain -obviously- prices, such as price ex VAT, etc. However, for some reason the pricing values are stored in my spreadsheet as strings, such as 18.21.
To be able to automatically calculate with these values, I need to convert values in these specific columns to numbers with a comma as divider. I'm new to Google Script, but with reading some other post etc, I managed to "write" the following script, which almost does the job:
function stringIntoNumber() {
var sheetActive = SpreadsheetApp.openById("SOME_ID");
var sheet = sheetActive.getSheetByName("SOME_SHEETNAME");
var range = sheet.getRange("R2:R");
range.setValues(range.getValues().map(function(row) {
return [row[0].replace(".", ",")];
}));
}
The script works fine as long as only values with a dot can be found in column R. When values that belong to the range are changed to values with a comma, the script gives the error:
TypeError, can't find the function Replace.
Select the column you want to change.
Goto Edit>Find and Replace
In Find area put "."
in Replace with area put ","
The error occurs because .replace is a string method and can't be applied to numbers. A simple workaround would be to ensure the argument is always a string, there is a .toString() method for that.
in your code try
return [row[0].toString().replace(".", ",")];
The locale of your spreadsheet is set to a country that uses commas to seperate decimal places. Zapier however seems to use dots and therefore google sheets interprets the data it gets from Zapier as strings since it can't interpret it as valid numbers.
If you change the locale to United States (under File/Spreadsheet settings) it should work correctly. But you may not want to do that because it can cause other issues.
You got a TypeError because the type was number and not string. You can use an if statement to check the type before calling replace. Also you should convert the type to 'number' to make sure it will work correctly independent of your locale setting.
range.setValues(range.getValues().map(function(row) {
if(typeof row[0] === "string") return [Number(row[0].replace(",", "."))];
else return row;
}));
In this case I convert , to . instead of the other way around since the conversion to number requires a ..
Click on Tools > Script Editor.
Put this on your macros.gs (create one if you don't have any):
/** #OnlyCurrentDoc */
function ReplaceCommaToDot() {
var range = SpreadsheetApp.getActiveRange();
var col = range.getColumn();
var row = range.getRow();
function format(str) {
if(str.length == 0) return str;
return str.match(/[0-9.,]+/)[0]
.replace('.','')
.replace(',','.');
}
var log = [range.getRow(), range.getColumn()];
Logger.log(log);
var values = range.getValues()
for(var row = 0; row < range.getNumRows(); row++){
for(var col = 0; col < range.getNumColumns(); col++){
values[row][col] = format(values[row][col]);
}
}
range.setValues(values);
}
Save. Go back to the spreadsheet, import this macro.
Once the macro is imported, just select the desired range, click on Tools > Macro and select ReplaceCommaToDot
Note: This script removes the original ., and replaces , by .. Ideal if you are converting from US$ 9.999,99 to 9999.99. Comma , and whatever other text, like the currency symbol US$, were removed since Google Spreadsheet handles it with text formatting. Alternatively one could swap . and ,, like from US$ 9.999,99 to 9,999.99 by using the following code snippet instead:
return str.match(/[0-9.,]+/)[0]
.replace('.','_')
.replace(',','.')
.replace('_',',');
An alternative way to replace . with , is to use regex functions and conversion functions in the Sheets cells. Suppose your number is in A1 cell, you can write this function in any new cell:
= IF(REGEXMATCH(TO_TEXT(A1), "."), VALUE(REGEXREPLACE(TO_TEXT(A1), ".", ",")), VALUE(A1))
These functions do the following step:
Convert the number in the target cell to text. This should be done because REGEXMATCH expects a text as its argument.
Check if there is a . in the target cell.
If there is a ., replace it with ,, and then convert the result to a number.
If there is no ., keep the text in the target cell as is, but convert it to a number.
(Note : the Google Sheets locale setting I used in applying these functions is United States)
I have different solution.
In my case, I`m getting values from Google Forms and there it is allowed use only numbers with dot as I know. In this case when I capture data from Form and trigger script which is triggered when the form is submited. Than data is placed in specific sheet in a specific cell, but formula in sheet is not calculating, because with my locale settings calculating is possible only with a comma not dot, that is coming from Google Form.
Then I use Number() to convert it to a number even if it is already set as a number in Google Forms. In this case, Google Sheets script is converting number one more time to number, but changes dot to comma because it is checking my locale.
var size = Number(sizeValueFromForm);
I have not tested this with different locale, so I can`t guarantee that will work for locale where situation is opposite to mine.
I hope this helps someone. I was looking for solution here, but remembered that some time ago I had similar problem, and tried this time too and it works.
=IF(REGEXMATCH(TO_TEXT(F24);"[.]");REGEXREPLACE(F24;"[.]";",");VALUE(F24))
Works for me
If find dot replace with comma if not, put value
I'm using method "Ext.util.Format.number" to convert a value to string, according to a specific format.
But this method add extra (parasite) decimal.
With this code :
var strValue = Ext.util.Format.number(value, this.displayFormat);
For example if
displayFormat = "0,000.00############"
value = 102.15
After conversion, strValue is not equals to 102.15 but to 102.15000000000001
Is there any way to be sure that "Ext.util.Format.number" never add extra/parasite decimal ?
Thanks
Since 102.15 and 102.15000000000001 are not distinguishable(*) in JavaScript, it's up to you to choose a number format that does not include that many digits. Ext.util.Format.number has no way to determine the correct output.
(*) try 102.15 === 102.15000000000001 in your javascript console - it returns true
Do parseFloat(strValue) after that formatting. I think thats what you are looking for.
I have a little problem with my jQuery script: instead of counting up all variables, the script puts them next to each other. How do I count up the variables? (I am new to jQuery, so maybe I overlooked something or made a stupid mistake).
This is the line of code that should count up the variables.
totalcost = ((commissioncost + paypalcost) + qrticketcost);
http://jsfiddle.net/bsuh5q8k/1/
Thanks.
Often when you retrieve a value from a field using jquery's .val(), you'll get the string value (String type) instead of the numeric value you desire here. For instance, the field value may be 37.50, but you're getting "37.50" from .val()
So when you do this:
commissioncost = $('input[name=price]').val();
You'll get the String value.
So instead, try this:
commissioncost = Number($('input[name=price]').val());
This will convert/cast the value into a Number for you.
Also, a word of caution: just be sure whatever value is in that field, it can be evaluated as a Number, otherwise comissioncost will equal "NaN" (not a number) and will give you the same grief you're experiencing now. The rudimentary method to check if the type conversion was successful is:
commissioncost = Number($('input[name=price]').val());
if(isNaN(commissioncost)){
// oops, value wasn't a number!
}else{
// hooray! value was a number (most of the time - but that's a longer discussion)
}
commissioncost is being treated as a string. So when you add it thinks you're wanting to concatenate.
When you pull it from the input, explicitly tell Javascript that it's a number/float.
commissioncost = parseFloat($('input[name=price]').val());
I'm trying to write a userscript for a game I'm playing. It uses this piece of HTML code:
<td valign="center">
<b>ten-leaf clover</b>
(4 left in stock for today)
</td>
This is a picture of what we're talking about:
The script should search for a string containing the words "left in stock for today", then look for an integer within this string. (The '4' is not constant, it changes every day.) Lastly, I would like to store this integer as a variable, so I can replace the '1' in the input field. Like this:
var clover = EnterCodeHere
$("input.text[name='quantity']").val(clover);
You can used a regex like so:
var textToSearch = $("td").innerHtml(); //You'll need a better selector than this. better to use a class or id
var clover = parseInt(textToSearch.match(/\d+\s*left in stock for today/)[0].match(/\d+/)[0]);
$("input.text[name='quantity']").val(clover);
You may want to check the array isn't empty before just taking the first value but if your confident it'll be there should be grand.
i have a table like below which each content is input pop-up
on square i spot you see on last digit have 1,2,8,9 format.
in my html the content of table is value of Posisi
Nomor Rak
<br><input type="text" id="posisi" readonly/></br>
that automaticly i pick using
<td class="data206"><div align="center"><input class="data206" type="button" onclick="popup_window_show('#sample', { pos : 'tag-right-down', parent : this});setvalue(this.value);" value="A1.7.8" /></div></td>
for an example.
so my pop-up like this
my purpose to bind the last digit and then i can manipulate line value. So for an idea script will like below
$(document).ready(function(){
var posisi = $("#posisi").val();
if (posisi== like "1" or like "2" or like "8" or like "9" ){
$("#line").val("9")
}
});
My problem: I don't know how to bind the last digit in jquery..to make conditonal that $("#posisi") last digit value between 1 or 2 or 8 or 9. if this conditional true i can add value in $("#line").val("whatever i want")
need help with an example will be appreciate
Your var posisi will contain a string like "A1.7.8" and you can easily get the last character of string. This may help
How can I get last characters of a string using JavaScript
There are a few more tips which may help.
It seems that you do not want to wrap the code in document.ready. I think you want to get the last digit value on every click. so get the value in "popup_window_show" function or function you are using to show popup.
Moreover if you want to make calculation on that number i.e 1,2,8,9 then convert it into integer form first.
var posisi = $("#posisi").val();
var regex = /\.(\d+)\.?$/;
// Catches the last set of digits following a period.
// Allowing for an additional period at the end.
var matches = posisi.match(regex);
if (matches) {
var lastNumber = parseInt(matches[1], 10);
// Do something
$("#line").val(lastNumber);
}