STR in JS
Description
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
Return Type
Examples
Last updated
Was this helpful?