'Format Number in Google Script
How can I make a form submission like 1234 return 1,234?
Right now
var price = 1234
PLEASE help turn this into 1,234
Solution 1:[1]
Just use toLocaleString as in
var n = 1234;
alert(n.toLocaleString());
The language spec says
Produces a String value that represents this Number value formatted according to the conventions of the host environment’s current locale.
so it should format the number with the user's preferred digit grouping, and the right decimal separator.
Solution 2:[2]
Try a function like this.
function comma(num){
while (/(\d+)(\d{3})/.test(num.toString())){
num = num.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return num;
}
Then, call it with
comma(1234); // "1,234"
Solution 3:[3]
You're asking about how to control the format of responses in Google Forms: Google Forms does not give you any way to manage the format of responses that are accepted.
You can control the format of values in the spreadsheet that accepts the responses, and you need no script for that. To do so, go to the response spreadsheet, select the cells in the column that contains the numbers you are interested in, and select your desired format from the menu.
This will affect how the numbers appear in the spreadsheet only - any script handling responses will be dealing with a javascript Number object, which has no format. See the answers from Mike or Overcode for options to generate a formatted string from a Number.
Solution 4:[4]
var price = 1234;
price.setNumberFormat("#,000.00");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mike Samuel |
| Solution 2 | Richard Frank |
| Solution 3 | Mogsdad |
| Solution 4 | Abie Alvarez |
