Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Convert numeric value to string, with the specified maximum number of decimals.
- // Trailing zeros to the right of the decimal point will be removed.
- function toStringWithoutTrailingDecimals2(num as Numeric, maxDecimals as Number) as String {
- var factor = Math.pow(10, maxDecimals).toDouble();
- // Math.round(...) can be replaced with the rounding algorithm of your choice
- // e.g.
- // truncation: var roundedAndScaledNum = (num * factor).toNumber()
- // ceiling: var roundedAndScaledNum = Math.ceil(num * factor).toNumber()
- var roundedAndScaledNum = Math.round(num * factor).toNumber(); // [*]
- // NOTE: use toLong() if num or maxDecimals are large enough to overflow a Number
- // Using toNumber() gives us up to 10 digits to work with, while toLong() should give us up to 20 digits
- num = roundedAndScaledNum;
- var numDecimals = maxDecimals;
- while (numDecimals > 0) {
- if (num % 10 != 0) {
- break;
- }
- num = num / 10;
- numDecimals--;
- }
- // [*] We've already rounded above, avoid rounding again to prevent possible inconsistencies.
- //
- // Instead, manually convert the number to a string. One side advantage is that we can change
- // the rounding algorithm above without affecting the correctness of the output.
- // (e.g. we could decide to use banker's rounding, and the output would still be correct)
- //
- // To save memory for code we could move this line up to avoid
- // having to declare roundedAndScaledNum as a separate local variable.
- // This is just here for "clarity."
- var str = roundedAndScaledNum.toString();
- // remove extra digits
- str = str.substring(0, str.length() - (maxDecimals - numDecimals)) as String;
- // add decimal point
- if (numDecimals > 0) {
- var len = str.length();
- str = str.substring(0, len - numDecimals) + "." + str.substring(len - numDecimals, len);
- }
- return str;
- }
Advertisement
Add Comment
Please, Sign In to add comment