ANS-1201 · SUITESCRIPT DEVELOPMENT
How to Handle NaN Results from parseFloat in NetSuite SuiteScript?
A custom JavaScript utility function can standardize numeric parsing in NetSuite SuiteScript by converting NaN results to zero, ensuring robust data handling.
Short answer
While NetSuite's SuiteScript environment uses standard JavaScript parseFloat behavior, which returns NaN for null, undefined, or empty string inputs, a custom utility function can be implemented. This function checks for NaN results and converts them to 0, providing consistent numeric output for calculations.
Scenario
Developers often encounter situations where parseFloat returns NaN (Not-a-Number) when processing various field values in NetSuite SuiteScript. This can occur with null, undefined, or empty string inputs, leading to unexpected calculation errors or script failures. While parseFloat correctly handles percentage signs by extracting the numeric value, a robust solution is needed for non-numeric inputs.
Solution
The standard JavaScript parseFloat function, used within NetSuite SuiteScript, exhibits specific behaviors when parsing various input types. For instance, parseFloat('55.05%') will correctly return 55.05. However, when parseFloat encounters null, undefined, or an empty string (''), it returns NaN (Not-a-Number).
To mitigate NaN results and ensure a numeric output, a custom utility function can be implemented. This function checks if the parsed value is NaN and, if so, defaults it to 0.
An example of such a custom function is:
function forceParseFloat(valueToParse) {
var parsedValue parseFloat(valueToParse);
if (isNaN(parsedValue)) {
parsedValue 0;
}
return parsedValue;
}This custom forceParseFloat function ensures that inputs like null, undefined, and '' (empty string), which would typically result in NaN when passed directly to parseFloat, will instead return 0. This provides a consistent numeric value for further calculations.
Expert NetSuite Support
Need help with this NetSuite issue?
SuiteScript Development consulting and configuration support
