A Loser
A Loser

Reputation: 11

Translating Excel Macro to Google Apps Script

I used a macro in an excel sheet to make a custom rounding function for a special calculator. I want to upload the calculator sheet to my google drive so that I can share it as a resource. However, the excel language doesn't translate to the Google Apps Script language and I can't figure out how to adjust it.

I'm no code expert, seeing as I copied the base code from excel and tweaked slightly and probably got lucky in making it work. But I tried to translate the code to work in google apps script and never got it to run without an error.

This is the excel code that gave me a successful function.

Function pokeRound(pValue As Double) As Double

Dim LWhole As Long
Dim LFraction As Double

'Retrieve integer part of the number
LWhole = Int(pValue)

'Retrieve the fraction part of the number
LFraction = pValue - LWhole

If LFraction <= 0.5 Then
  pokeRound = LWhole
Else
  pokeRound = Round(pValue, 0)
End If

End Function

This is my attempt at translation that doesn't work

function pokeRound() {
// Retrieve integer part of the number
var LWhole = (pValue);

// Retrieve the fraction part of the number
var LFraction = pValue - LWhole;
 If (LFraction <= 0.5)
   pokeRound = LWhole;
 Else
 (pokeRound = Round(pValue, 0));
};

The result of this function is a custom rounding method. Normal rounding up would mean 88.5 rounds to 89. This function instead rounds 88.5 to 88 and rounds 88.51 to 89. Could anyone help me translate this to work in Google Apps Script?

Upvotes: 0

Views: 263

Answers (1)

Cooper
Cooper

Reputation: 64062

How about this?

function pokeRound(v) {
  var v=v||1.63;
  var w=Math.floor(v);
  var f=v-w;
  if(f<=0.5) {
    return w;
  }else{
   return Math.round(v);
  }
}

Upvotes: 2

Related Questions