Formatting strings with positive or negative numbers can be achieved using Utilities.formatString

Looking to enhance the visual representation of numeric string data by displaying it in different colors based on whether the number is positive or negative.

Current code snippet:

var url = 'https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxx/edit#gid=xxxxxxxxx';
var spreadSheet = SpreadsheetApp.openByUrl(url);
var allSheets = spreadSheet.getSheets();
var theSheet = allSheets[1];
var lastRow = theSheet.getLastRow();
var lastColumn = theSheet.getLastColumn();
var sheetData = theSheet.getSheetValues(1, 1, lastRow, lastColumn);

var rawData = sheetData[1][1];
var calcData = sheetData[1][1] / sheetData[0][1];
var formattedData = Utilities.formatString("%+1.2f%", calcData * 100);

Result for formattedData:

+12.1%

Considering formatting this output with green letters for positive numbers and red letters for negative numbers.

Related question: .setNumberFormat is not working in Google Apps Script

Answer №1

When working with your script, it's important to note that the formattedData variable holds the string value. If you're looking to change the font color within a cell, you'll need to assign the value directly to that cell. Here is a proposed method for changing font color within a cell:

If your script involves using theSheet, consider utilizing the following sample script:

Sample script:

var calcData = -0.1234;
theSheet
  .getRange("A1")
  .setValue(calcData)
  .setNumberFormat('+0.00%;-0.00%;0.00')
  .setFontColor(calcData > 0 ? "green" : "red");
  • In this example script, the value of -12.34% will be placed in cell "A1" and the font color will be set to red.

  • If var calcData = 0.1234; is used instead, the value +12.34% will be in cell "A1" with the font color set to green.

  • For those wanting to incorporate Utilities.formatString, here's a sample script to refer to:

    var calcData = -0.1234;
    var formattedData = Utilities.formatString("%+1.2f%", calcData * 100);
    theSheet
    .getRange("A1")
    .setValue(formattedData)
    .setFontColor(calcData > 0 ? "green" : "red");
    

Note:

  • This example serves as a basic guide. Be sure to tailor it to suit your specific needs.

References:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Codeigniter not functioning properly with Ajax

I am trying to implement this javascript function $('a[name=deleteButton]').on('click', function () { arr=[]; var arr = $("input[name='post[]']:checked").map(function() { return this.value; }). ...

Can you explain the concept of (A == B == C) comparison in JavaScript?

Surprisingly, the comparison I expected to fail was this: var A = B = 0; if(A == B == 0) console.log(true); else console.log(false); To my surprise, it doesn't return true. What's even more astonishing is that console.log((A == B == ...

Creating a dropdown menu in React

Imagine having an options array like the one below: options = [ { name: 'My profile' }, { name: 'Sign out' } ] public selectOptions(showOptions: boolean) { this.setState({ showOptions: !showOptions }) return options.map((opt ...

What is the best method for verifying that audio has not been loaded correctly?

After creating a script to scrape for mp3 audio file URLs and load them into my HTML audio element's src, I encountered an issue where some of the URLs were not functioning properly. As a result, the audio was unable to execute the load() method since ...

Creating a Next.js application that retrieves mock data and dynamically presents it on the user interface

I've been attempting to retrieve some placeholder data from an API and showcase it on the screen, but unfortunately nothing is appearing. Interestingly, the data does show up in the console, just not on the actual screen. function Shop() { const [pr ...

What could be causing my jQuery to fail when the page first loads?

My script only seems to work when the input changes, but I want it to start working as soon as the page loads and then continue to update when the input changes. Can anyone help me figure out what's wrong with my script? <script src="http://co ...

The issue with the Angular custom checkbox directive arises when using it within an ng-repeat

A personalized directive has been developed for checkboxes that is applicable throughout the application. The code for creating the checkbox is as follows: JS angular.module("myApp") .component("ngCheckbox", { template: '<di ...

Creating a Loopback API that seamlessly integrates with Ember.js

Exploring the use of Loopback to create an API that communicates with Ember. Ember expects JSON data to be enclosed in 'keys', such as for an account: { account: { domain: 'domain.com', subdomain: 'test', title: ...

nuxt-link: take me to the identical position with the hash in the URL

I'm facing an issue with the <nuxt-link> component in my Nuxt application: The first time I click on the link, everything works perfectly and the page is changed as expected. However, if I scroll down a bit and try clicking the link again, noth ...

Tips on identifying the method to import a module

Currently, I am including modules into my Node project like this: import * as name from "moduleName"; Instead of the old way: var name = require("moduleName"); In the past, we used require in Node projects. My question is, is there a difference in ...

Oops: [ERR_HTTP_HEADERS_SENT]: Headers can't be set once they've been sent to the client, please fetch again

I'm encountering an issue with my code where I am unable to make a fetch request when invoking sendPushMessages(message) due to HTTP ERRORS, but I am unsure of the root cause. The console is displaying the following error message: Error [ERR_HTTP_HEA ...

Differentiating a path element in SVG by dynamically adding color using d3 and react

I have a unique SVG icon: <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <circle cx="12" cy="12" r="12" /> <path class="svg-fill" d="M12,2A10,10,0,1,0,22, ...

Consecutive POST requests in Angular 4

Can you assist me with making sequential (synchronous) http POST calls that wait for the response from each call? generateDoc(project, Item, language, isDOCXFormat) : Observable<any> { return this.http.post(this.sessionStorageService.retriev ...

javascript to retrieve data by reducing

Here is the code snippet I am working with: var points = 4; var yModifier = []; for (var i = 0; i <= points; i++) { yModifier.push([]); }; yModifier.forEach( (a, j) => { var start = j; var end = start + points; fo ...

Incorporate a button within a listview on Kendoui to trigger the opening of a modal window

I am seeking assistance on how to insert a button on each element of a Listview (PHP/Json) result. When clicked, this button should open a modal window where the customer can input reservation details such as Date, Adults, and Children. Below is the JavaSc ...

Is it possible to incorporate Bluetooth connectivity into an HTML5/JS Web application?

Currently, I have developed a WebApp using HTML5, JS, and Jquery. I am now looking to integrate Bluetooth functionality into it to enable data transfer to another Bluetooth-enabled device. After downloading the Bluetooth Dev Kit and going through numerous ...

Ways to retrieve information from a intricate JSON structure?

Can anyone help me understand why I am unable to access the data in the detail option of the JSON? My goal is to load the firstName, lastName, and age into a list for each object. var data = { "events": [{ "date": "one", "event": "", "info ...

How can Node.js handle an upgrade request effectively?

Dealing with a websocket 'upgrade' event from a Node.js http server presents an interesting challenge - The upgrade handler takes the form of function(req, socket, head) - Is there a method to respond to this upgrade request without access to a r ...

The bootsrtap modal appears to be invisible and is not displaying on the screen

Having trouble implementing a code to display a bootstrap modal upon clicking a button. The modal is not showing up for some reason. Here is the code snippet: <button type="button" id="asd" data-toggle="modal" data-target= ...

Toggle the visibility of the search Div using Angular UI

When using angular UI buttons, users can select search criteria by choosing between Patient, ID, or Date. If Patient or ID is selected, the searchByText div will be shown. If Date is selected, the searchByText will be hidden and the SearchBydateRange wil ...