STR in JS
Description
Unfortunately, this functionality is not available in JS, but it can be implemented easily using the predefined functions for strings.
Sample Source Pattern
Implementation Example
function validLength(number, max_length, float_precision) {
var float_point = number.match(/[\.][0-9]+/);
/*if the number does not have point float, checks if the float precision
* and current number are greater than max_length
*/
if(!float_point) return number.length + float_precision + 1 < max_length;
//removes the '.' and checks if there is overflow with the float_precision
return number.length - float_point[0].trim('.').length + float_precision < max_length;
}
function STR(number, max_length, float_precision) {
var number_str = number.toString();
//if the expression exceeds the max_length, returns '**'
if(number_str.length > max_length || float_precision > max_length) return '**';
if(validLength(number_str, max_length, float_precision)) {
return number.toFixed(float_precision);
}
return number.toFixed(max_length - float_precision);
}
Arguments
number
: Float expression with a decimal point.
max_length
: Length that the returning expression will have, including point notation, decimal, and float parts.
float_precision
: Is the number of places to the right of the decimal point.
Return Type
String.
Examples
CREATE OR REPLACE FUNCTION STR(number float, max_length float, float_precision float)
RETURNS string
LANGUAGE JAVASCRIPT
AS
$$
function validLength(number, max_length, float_precision) {
var float_point = number.match(/[\.][0-9]+/);
if(!float_point) return number.length + float_precision + 1 < max_length;
return number.length - float_point[0].trim('.').length + float_precision < max_length;
}
function STR(number, max_length, float_precision) {
var number_str = number.toString();
if(number_str.length > max_length || float_precision > max_length) return '**';
if(validLength(number_str, max_length, float_precision)) {
return number.toFixed(float_precision);
}
return number.toFixed(max_length - float_precision);
}
return STR( NUMBER, MAX_LENGTH, FLOAT_PRECISION );
$$;
SELECT STR(12345.674, 12, 6);
Last updated