The NumberUtils module provides a collection of helper functions for performing common number-related operations in your server-side JavaScript code. It simplifies tasks like formatting, rounding, parsing, and validating numeric values-ensuring consistency and reducing boilerplate across your application.
Whether you're working with prices, percentages, calculations, or user input, the NumberUtils module offers reliable utilities for handling numbers with precision and ease.
Note: The NumberUtils module is globally available via kd.numberUtils
The NumberUtils module is lightweight and designed to be used wherever numeric logic is needed in your server-side code.
Generates a random unique ID string based on the current timestamp and a random number.
var uniqueId = kd.numberUtils.generateId();
// Returns something like: "a7npor1686924719zll"
Formats a number as a quantity with thousands separators and no decimal places.
var formattedQuantity = kd.numberUtils.formatQuantity(1234567);
// Returns: "1,234,567"
var invalid = kd.numberUtils.formatQuantity(null);
// Returns: ""
Formats a number as a currency value with dollar sign, thousands separators, and appropriate handling of negative values.
value (Number, required): The number to format as currency.opts (Object, optional): Formatting options with the following propertiesminimumFractionDigits (Number, optional): The minimum number of decimal places to show. Defaults to 2.var price = kd.numberUtils.toCurrency(1234.56);
// Returns: $1,234.56
const negativePrice = kd.numberUtils.toCurrency(-1234.56);
// Returns: ($1,234.56)
var customDecimals = kd.numberUtils.toCurrency(1234.5, { minimumFractionDigits: 3 });
// Returns: $1,234.500
const invalid = kd.numberUtils.toCurrency(null);
// Returns: ""
Converts a value to a number with the specified number of decimal places.
value (Any, required): The value to convert to a number.decimals (Number, optional): The number of decimal places.var number = kd.numberUtils.toNumber("123.456", 2);
// Returns: 123.46 (rounded to 2 decimal places)
Rounds a number to two decimal places for currency calculations, ensuring proper handling of floating-point precision issues.
value (Number, required): The number to round for currency calculations.var rounded = kd.numberUtils.toCurrencyNumber(1.9999999999);
// Returns: "1.99"
var wholeNumber = kd.numberUtils.toCurrencyNumber(2);
// Returns: "2.00"
var invalid = kd.numberUtils.toCurrencyNumber(null);
// Returns: ""