How to convert text to number in Google Script - google-apps-script

I am a new user of Google Script and scripts in general.
My company has Office licences and for strategics reasons it wants to use google services.
My problem is that we extract from a software various data containing numbers. When we paste these datas on a spreadsheet the negatives numbers format is not recognized because they are like :
screenShot
I would like to apply the script only on a selection of active spreadsheet and the texte "1 234,56-" become a number "-1 234,56". The selection may contains positive number as "1 234,56".
Thank you for your help.
Best regards,
Anthony.

=VALUE(REGEXREPLACE(REGEXREPLACE(TEXT(A1; "0000.00"); "\s"; ""); "(.*?)-"; "-$1"))
This will first convert the number to a text string, then remove the whitespace character, then move the - sign in front of the number, and lastly convert it back to a numeric value.
Before:
1 234,56-
352,90
2 342,89-
24,0
45,00-
After (and you can use Sheets' number formats to further alter if needed):
−1234,56
352,9
−2342,89
24
−45

if you're range is not too long you can try something like that :
How to replace text in Google Spreadsheet using App Scripts?
i have the same probleme for a file of 5k line to remplace "." by "," it work but need a bit time :)
i hope this will help you
Best regards

Related

Change format of devise in apps script

I've a Sheets with many values in euro with 3 values after the decimal point (for exemple (2,154 €). I would like to convert this document in PDF to join it in mail.
When I convert it in temporary Sheet, this value change and I have 2.154 instead of. I would like to change the format of this cell.
So I decided to apply a setFormatNumber (.setNumberFormat('#,###.000 [$€]')) at this value but I don't get the result what I want. I obtain 2.154 € but I would like to have "," an not "." to separe entire to decimal values. I try to modify setFormatNumber by (.setNumberFormat('#,###,000 [$€]')) but my result is 2.154000 €.
I don't want to apply toString method and use replace method after because I think it's possible to have what I want by using this method.
Anyone can help me with that please ? I don't join my code because it's so long and, except the setNumberFormat, it's not interesting for you but if you need it, I can edit my post. Sorry for my english, I don't speak and write it very well.
Dots and commas have other meanings in the context of this “mask”-like parameter.
The numberFormat parameter of the setNumberFormat() is documented here.
According to the documentation, dots indicate where the decimal separator will be in the mask and commas indicate where the thousand separator will be.
The symbol of the decimal separator is however controlled according to the Spreadsheet locale settings.
You can change those settings via UI going to File > Settings > General > Locale or via Apps Scripts using the method SpreadsheetApp.getActive().setSpreadsheetLocale('XXXXX')

How to scrape HTML table into google sheets [duplicate]

This question already has answers here:
Scraping data to Google Sheets from a website that uses JavaScript
(2 answers)
Closed last month.
I would like to extract the Forward Dividend from a site such as Yahoo Finance and insert it into Google Sheets.
Example 1:
For ticker symbol AAPL: https://finance.yahoo.com/quote/AAPL?p=AAPL
I would like the the Google Sheet field to return: 0.82
Example 2:
For the same symbol: https://www.streetinsider.com/dividend_history.php?q=aapl
I would like it to return the 0.82 amount from the table.
Is this even possible?
Since you mentioned you want to use the built-in IMPORT* functions, I will answer from that perspective.
As with most Sheets-based scraping, it depends on the site. The two sites you have given behave very differently. Let's examine them separately:
1: Yahoo Finance - Possible
We view source and see that 0.82 is located in a table. This lets us use IMPORTHTML:
=INDEX(
SPLIT(
VLOOKUP(
"Forward Dividend & Yield",
IMPORTHTML("https://finance.yahoo.com/quote/AAPL?p=AAPL", "table", 2),
2,
),
" "
),
1
)
Import table data
Get the dividend row
Extract the dividend yield value.
2: Street Insider - Not Possible
You might think that since the View Source lets us see the table in the browser, we should be able to use IMPORTHTML() again. Sadly this is not the case. The server-side seems to detect that you're not using a browser to access the .php, and it will display an empty page. Google sheets uses a different user agent from your own browser.
The only thing I can recommend if you need to use the IMPORT* functions is that you find a different site to pull the data from.

A function to format numbers as written in Germany

I am writing my first script for an invoice template based on a Google Doc.
It works fine. I need to use it in Germany so I need to be able to format the prices in the way they are shown in Germany.
I have written a short function to do this but am interested in whether there is a better or more obvious way of achieving this.
// this formats numbers as used in Germany
function numberToGerman(number){
number = Utilities.formatString("%d.%d,%02d", number/1000, number%1000, number%1*100);
return number;
}
It has a problem above 999.999,99 or below 1.000,00 at the moment but I hope there is a better solution out there.
Here is a slight modification of the answer by Elias Zamaria, replacing separators and ensuring exactly two decimals:
function numberToGerman(number){
var parts = number.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");
parts[1] = ((parts[1] || "") + "00").slice(0,2);
return parts.join(",");
}
The parts are the integer and fractional parts. Groups of three digits are processed by the regex, which places dots accordingly. The fractional parts is expanded/truncated to two places.
Remarks
Unfortunately, number.toLocaleString("de-DE") is not yet supported by Google Apps Script. One can use number.toLocaleString() but then the performance depends on someone having set the correct locale. Also, options concerning decimal places aren't supported either, so this doesn't help that much.
If this was to be used in a spreadsheet, you can apply appropriate formatting to cells either manually from the menu, or from a script: for example cell.setNumberFormat("#,###.00"). This looks like U.S.-style formatting, but once the locale of the spreadsheet is changed to Germany, it changes accordingly, e.g. 1.234.567,89.

Google Forms Quiz Score Data Format

New quizzing mode for google forms provides the scores in the form of a ratio with spaces in between (like this 5 / 7). However, the format of the cell is a number. So when I use dataRange.getValues(), I get only the first number (that is 5 in this example.) I tried setNumberFormat but received no permission error.
My goal is to somewhat get both numbers and actually complete the operation (5/7).
Thanks for your help.
I just found an answer. I used getDisplayValues() instead of getValues().

Applying "Automatic" number formatting

Is it possible to apply the 'Automatic' number format programmatically through GAS? My issue is that as I write columns of numbers, Sheets seems to attempt to apply appropriate formatting, but gets it wrong sometimes. That is, particular small integers (1 sometimes) will be formatted as dates. The range is being written in one myRange.setValues() method and I can't see any pattern to the mistakes and therefore don't see any way to prevent the surprise mis-formatting.
But, when I select the range in sheets and just click "Automatic" on the number format menu all returns to normal. It doesn't help to click that upfront as the writing of data somehow resets the format.
Despite the long-winded intro, my question is very simple: how to programmatically apply "Automatic" number formatting. I'm thinking this is very basic, especially since google and searches here have been no help.
My current fallback solution is to use myRange.setNumberFormat("0") as the format for the whole range. This is not ideal as some numbers are very large and are easier to read in scientific notation. There are also some text strings in the range, but these format properly regardless of format applied. I also would prefer to avoid having to iterate through the data and test for values to determine the best format, when it's just a couple clicks in the user interface.
we can use .setNumberFormat('General');
Below is the example:
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange("B:B").setNumberFormat("General");
I use copyFormatToRange to copy/apply Automatic format:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var source_cell = sheet.getRange("A1");//A1: cell having automatic format
source_cell.copyFormatToRange(sheet,1,1,2,2);//copy format of cell A1 to cell A2
You can write an API that opens another spreadsheet, read any cell that having the automatic format.
var ss = SpreadsheetApp.openById(SpreadsheetId);//Id of another spreadsheet
Then use copyFormatToRange to your wanted cell.
I was having trouble finding anything documented, and tried pretty much everything suggested previously (null, 'General', the "magic" format of '0.###############', etc., etc.).
In my particular case, I had ranges previously set to strict plain text, which then got replaced with a checkbox data validation. Anytime the box was checked it was converted to the text "TRUE" instead of remaining a checkbox. 'General' and the "magic" format functionally worked fine, but did not actually set the format back explicitly to "Automatic".
I finally decided, why not just try this:
range.setNumberFormat('Automatic');
And it worked. This really should be documented, but at least a little bit of common sense lead me to the answer regardless.
If you don't have dates in the range, the below solution appears to be the best available option (without resorting to an API-based solution):
myRange.setNumberFormat('0.###############');
A zero-point-15x'#' seems to be a 'magic' number format that will allow very large numbers to show as scientific notation and smaller integers and decimals to show in the 'standard' format pre-application of number formatting. This is also the format that is returned for cells that contain non-dates formatted with the 'Automatic' selection in the user interface.
Adding or removing even one # will 'break the spell' and cause very large numbers to display in non-scientific notation. I also tested changes before the decimal place, but leaving the 15x#:
Also functional: myRange.setNumberFormat('#,##0.###############');
So there is some flexibility for prefixes.
Non-functional: myRange.setNumberFormat('#.###############');
The 0 is evidently required.
And finally,
Non-functional: savegameRange.setNumberFormat('0.##############[red]');
This turns numbers red, but breaks the 'magic' formatting. So no suffixes it appears.
Again, if you have dates in the range, this will not work as they will, not surprisingly, display as the underlying number. And potentially more problematic (but totally understandable), the only way to return them to date form is manually applying a date format, assuming you know which cells 'were' dates.
Complete replication of 'Automatic' number formatting requires traversing the range to find dates and apply desired date format, but otherwise applying the 'magic' format. (My original dataset was a mix of numbers and strings, so the simple approach given above works.)