Hubert P Tubbledale
Hubert P Tubbledale

Reputation: 21

Googlesheets how use a script to count the number of decimal places

So I have a box on a googlesheet that users enter a value into, which is then transferred onto a master spreadsheet by clicking a button. I have various conditions on the transfer already enacted, but as the values are meant to be currency amounts I wish to ensure that they are a maximum of 2 decimal places upon entry, rather than rounding them.

Is there a script function that would allow me to count the number of decimal places?

Upvotes: 1

Views: 876

Answers (1)

QHarr
QHarr

Reputation: 84465

Pretty sure there must be an import statement of some sort for the GAS LibraryApp but I am new to this. All functions are courtesy of that site/Bruce McPherson‎. The following uses the appropriate functions to reproduce the InStrRev functionality found in VBA. It returns the position of the "." in the input string.

TODO: There should be a test added that "." is indeed present.

Improvements welcomed.

function fixOptional(arg, defaultValue) {
    if (isUndefined(arg)) {
        return defaultValue;
    } else {
        return arg;
    }
}

function Len(v) {
    return CStr(v).length;
}
function IsMissing(x) {
    return isUndefined(x);
}

function CStr(v) {
    return v === null || IsMissing(v) ? "" : v.toString();
}

function isUndefined(arg) {
    return typeof arg === "undefined";
}

function InStrRev(inThisString,lookFor,optStart,optCompare) {
  var start = fixOptional (optStart, -1);
  var s = CStr(inThisString);
  start = start == -1 ? Len(s) : start ;
  return (s && lookFor) ? s.lastIndexOf(lookFor,start-1)+1 : 0;
}

Logger.log(InStrRev("20.00",".")-1);

Upvotes: 1

Related Questions