underscore.string
underscore.string copied to clipboard
_.numberFormat not support the number is a float.
the _.numberFormat not support the number is a float.
example:
var tmpNumber = 10000.123; _.numberFormat(tmpNumber )
it println: 10,000
i want it output 10,000.123
when we use this function, i don't care the number of variable "tmpNumber" is an int or float , also i don't want it output an int string. I only hope it format the int part of variable "tmpNumber", I want the output is the "10,000.123"
but now this function not support this. i modify the function used in my app.
on below :
numberFormat : function(number, dec, dsep, tsep) {
if (isNaN(number) || number == null) return '';
//begin: modify here
if(!isNaN(parseInt(dec,10))){
number = number.toFixed(~~dec);
}else{
number = number.toString();
}
//end
tsep = typeof tsep == 'string' ? tsep : ',';
var parts = number.split('.'), fnums = parts[0],
decimals = parts[1] ? (dsep || '.') + parts[1] : '';
return fnums.replace(/(\d)(?=(?:\d{3})+$)/g, '$1' + tsep) + decimals;
},
line 518 of test/strings.js has:
equal(_.numberFormat(1000.754), '1,001');
seems to show that underscore.string is rounding up the floating point.
So, I think an extra parameter -- no round will be needed. What do you think?
Thanks. I see the code modifyed like this: numberFormat : function(number, dec, dsep, tsep, noRound) Maybe, this code is better :numberFormat : function(number, dec, dsep, tsep) ,
By the parameter "Dec" to determine that the "number" need for round operation. Then the parameters is consistent .
The "dec" parameter Can be explained as below for semantic coding and logic :
- dec == null : not need round the "number" input
- dec == “a number of integer” : it's need to round
then that : _.numberFormat(10000.123,3,'.',',',true) can be simplifyed as _.numberFormat(10000.123)
because the "dsep", "tsep" has their default values (“.” and ',' )
I'm sorry for my poor english .haha ^_^
I have to agree with @pronebel
It is much cleaner to require decimal precision rather than assume the user wants to round. numberFormat should check if "dec" is provided, if it is not then it should not round the number.