Change format of devise in apps script - google-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')

Related

How to convert text to number in Google 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

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.

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.)

Formating Output in Information Design Tool

When working with IDT 4.1 and when making a query in business layer, is it possible to format the yielded numbers? What I mean is - the output looks something like "1.9982121921**E7**" (please noctice E7 part). I would like BO to display the whole number without any suffixes.
Additionally, it would be even better to add a delimiter after thousands, millions,...
Is 1.9982121921**E7** the value that is returned from the database? Thus not a number but a string (alphanumeric)? In that case, you'll have to change the select statement and use a database function to trim the non-numeric characters off (e.g. SUBSTR, MID, LEFT, …).
Once you have numeric data, you can use the Display Format function to change the layout of your object.
If you're not happy with the predefined formats to choose from, you can always define a custom format. The formatting options are described in the Information Design Tool User Guide (links to the documentation for IDT in BI 4.1 SP3), section 12.10.23 Creating and editing display formats for business layer objects.
Right-click and object and select Create Display Format… from the context menu.
Or click the Create Display Format… button in the object's properties (located in the Advanced tab).
Set the type to numeric and enable the high precision check mark.

The search results in Drupal includes HTML Entities. How can I have a clean output?

How can I have a clean html ouput for search result pages? Each time I try to include special characters like "&" as part of the search term, I usually get results with "&" highlighted yet includes the HTML entity. Thus, the results has &, " etc...Here's a screenshot sample - http://min.us/mt3rOV5zVtOh6
Meanwhile, when I do my searches with "&" included in the search term, the result yields to having a clean output.
The piece of code in search-result.tpl.php
http://pastebin.com/zCmMJLNh
I've already tried several decoding functions but no success. Been trying to fix this for days already. The site is using Drupal 6 and the search module has been overridden.
You say "...the search module has been overridden" this could be the cause of why the search snippet remains htmlentityencoded on output ( e.g check_plain'd escaped html )
A better fix would be to find the cause in the modification, e.g a preprocess function that modifies the search snippet ( if any )
Alternatively, you could probably run the $snippet through decode_entities
i.e print decode_entities($snippet)
Assuming, the html is already escaped, as if not, can be a security risk.
See also: http://php.net/manual/en/function.html-entity-decode.php
and: http://www.php.net/manual/en/function.htmlspecialchars-decode.php
Well, you could try drupal_html_to_text to convert the snippet into plain text.
The right way is probably to figure out why those results aren't getting converted. Based on your comments it looks like the problem is only when you search specifically for "&". More specifically, it's the regex in the search.module (/modules/search/search.module - line 1188 in 6):
preg_match_all('/ ("([^"]+)"|(?!OR)([^" ]+))/', ' '. $keys, $matches);
It only matches spaces before the keyword (not after). You could modify the $keys here like:
if ($keys == '&') $keys = '&'
Or something like that (of course that means hacking core - meh).
You could also possibly add a form_alter via a module and modify the search form (see this link on how to add the form_alter). Then you could add a custom submit handler which would alter the search term in the form before it is submitted.