Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // get the number of decimals in a numeric value, up to a given precision (max decimals).
- // (to make this determination, the value is first rounded to the max number of decimals)
- function getNumberOfDecimals(num as Numeric, maxDecimals as Number) as Number {
- var factor = Math.pow(10, maxDecimals);
- num = Math.round(num * factor).toNumber();
- var count = maxDecimals;
- while (count > 0) {
- if (num % 10 != 0) {
- break;
- }
- num = num / 10;
- count--;
- }
- return count;
- }
- function toStringWithoutTrailingDecimals(num as Numeric, maxDecimals as Number) as String {
- return num.format("%0." + getNumberOfDecimals(num, maxDecimals) + "f");
- }
- function test() as Void {
- System.println(toStringWithoutTrailingDecimals(100, 2)); // 100
- System.println(toStringWithoutTrailingDecimals(100.5, 2)); // 100.5
- System.println(toStringWithoutTrailingDecimals(100.55, 2)); // 100.55
- System.println(toStringWithoutTrailingDecimals(100, 3)); // 100
- System.println(toStringWithoutTrailingDecimals(100.5, 3)); // 100.5
- System.println(toStringWithoutTrailingDecimals(100.55, 3)); // 100.55
- System.println(toStringWithoutTrailingDecimals(100.555, 3)); // 100.555
- System.println(toStringWithoutTrailingDecimals(100.5559, 3)); // 100.556
- // demonstrates the original value is properly rounded first
- System.println(toStringWithoutTrailingDecimals(100.5999, 3)); // 100.6
- }
Advertisement
Add Comment
Please, Sign In to add comment