Guest User

ciq-remove-trailing-zeros

a guest
Aug 15th, 2025
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // get the number of decimals in a numeric value, up to a given precision (max decimals).
  2. // (to make this determination, the value is first rounded to the max number of decimals)
  3. function getNumberOfDecimals(num as Numeric, maxDecimals as Number) as Number {
  4.     var factor = Math.pow(10, maxDecimals);
  5.     num = Math.round(num * factor).toNumber();
  6.     var count = maxDecimals;
  7.     while (count > 0) {
  8.         if (num % 10 != 0) {
  9.             break;
  10.         }
  11.         num = num / 10;
  12.         count--;
  13.     }
  14.     return count;
  15. }
  16.  
  17. function toStringWithoutTrailingDecimals(num as Numeric, maxDecimals as Number) as String {
  18.     return num.format("%0." + getNumberOfDecimals(num, maxDecimals) + "f");
  19. }
  20.  
  21. function test() as Void {
  22.     System.println(toStringWithoutTrailingDecimals(100, 2)); // 100
  23.     System.println(toStringWithoutTrailingDecimals(100.5, 2)); // 100.5
  24.     System.println(toStringWithoutTrailingDecimals(100.55, 2)); // 100.55
  25.     System.println(toStringWithoutTrailingDecimals(100, 3)); // 100
  26.     System.println(toStringWithoutTrailingDecimals(100.5, 3)); // 100.5
  27.     System.println(toStringWithoutTrailingDecimals(100.55, 3)); // 100.55
  28.     System.println(toStringWithoutTrailingDecimals(100.555, 3)); // 100.555
  29.  
  30.     System.println(toStringWithoutTrailingDecimals(100.5559, 3)); // 100.556
  31.     // demonstrates the original value is properly rounded first
  32.     System.println(toStringWithoutTrailingDecimals(100.5999, 3)); // 100.6
  33. }
Advertisement
Add Comment
Please, Sign In to add comment