Guest User

ciq-remove-trailing-zeroes

a guest
Aug 16th, 2025
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Convert numeric value to string, with the specified maximum number of decimals.
  2. // Trailing zeros to the right of the decimal point will be removed.
  3. function toStringWithoutTrailingDecimals2(num as Numeric, maxDecimals as Number) as String {
  4.     var factor = Math.pow(10, maxDecimals).toDouble();
  5.  
  6.     // Math.round(...) can be replaced with the rounding algorithm of your choice
  7.     // e.g.
  8.     // truncation: var roundedAndScaledNum = (num * factor).toNumber()
  9.     // ceiling: var roundedAndScaledNum = Math.ceil(num * factor).toNumber()
  10.     var roundedAndScaledNum = Math.round(num * factor).toNumber(); // [*]
  11.     // NOTE: use toLong() if num or maxDecimals are large enough to overflow a Number
  12.     // Using toNumber() gives us up to 10 digits to work with, while toLong() should give us up to 20 digits
  13.  
  14.     num = roundedAndScaledNum;
  15.     var numDecimals = maxDecimals;
  16.     while (numDecimals > 0) {
  17.         if (num % 10 != 0) {
  18.             break;
  19.         }
  20.         num = num / 10;
  21.         numDecimals--;
  22.     }
  23.  
  24.     // [*] We've already rounded above, avoid rounding again to prevent possible inconsistencies.
  25.     //
  26.     // Instead, manually convert the number to a string. One side advantage is that we can change
  27.     // the rounding algorithm above without affecting the correctness of the output.
  28.     // (e.g. we could decide to use banker's rounding, and the output would still be correct)
  29.     //
  30.     // To save memory for code we could move this line up to avoid
  31.     // having to declare roundedAndScaledNum as a separate local variable.
  32.     // This is just here for "clarity."
  33.     var str = roundedAndScaledNum.toString();
  34.  
  35.     // remove extra digits
  36.     str = str.substring(0, str.length() - (maxDecimals - numDecimals)) as String;
  37.     // add decimal point
  38.     if (numDecimals > 0) {
  39.         var len = str.length();
  40.         str = str.substring(0, len - numDecimals) + "." + str.substring(len - numDecimals, len);
  41.     }
  42.     return str;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment