Adding OpenLayers.Number.format for string formatted numbers. Thanks for initiating this Andreas. Nice pairing with you. r=me (closes #1253)
git-svn-id: http://svn.openlayers.org/trunk/openlayers@5686 dc9f47b5-9b13-0410-9fdd-eb0c1a62fdaf
This commit is contained in:
@@ -213,6 +213,19 @@ if (!String.prototype.camelize) {
|
||||
*********************/
|
||||
|
||||
OpenLayers.Number = {
|
||||
|
||||
/**
|
||||
* Property: OpenLayers.Number.decimalSeparator
|
||||
* Decimal separator to use when formatting numbers.
|
||||
*/
|
||||
decimalSeparator: ".",
|
||||
|
||||
/**
|
||||
* Property: OpenLayers.Number.thousandsSeparator
|
||||
* Thousands separator to use when formatting numbers.
|
||||
*/
|
||||
thousandsSeparator: ",",
|
||||
|
||||
/**
|
||||
* APIFunction: OpenLayers.Number.limitSigDigs
|
||||
* Limit the number of significant digits on a float.
|
||||
@@ -231,6 +244,60 @@ OpenLayers.Number = {
|
||||
fig = parseFloat(num.toPrecision(sig));
|
||||
}
|
||||
return fig;
|
||||
},
|
||||
|
||||
/**
|
||||
* APIFunction: OpenLayers.Number.format
|
||||
* Formats a number for output.
|
||||
*
|
||||
* Parameters:
|
||||
* num - {Float}
|
||||
* dec - {Integer} Number of decimal places to round to.
|
||||
* Defaults to 0. Set to null to leave decimal places unchanged.
|
||||
* tsep - {String} Thousands separator.
|
||||
* Default is ",".
|
||||
* dsep - {String} Decimal separator.
|
||||
* Default is ".".
|
||||
*
|
||||
* Returns:
|
||||
* {String} A string representing the formatted number.
|
||||
*/
|
||||
format: function(num, dec, tsep, dsep) {
|
||||
dec = (typeof dec != "undefined") ? dec : 0;
|
||||
tsep = (typeof tsep != "undefined") ? tsep :
|
||||
OpenLayers.Number.thousandsSeparator;
|
||||
dsep = (typeof dsep != "undefined") ? dsep :
|
||||
OpenLayers.Number.decimalSeparator;
|
||||
|
||||
if (dec != null) {
|
||||
num = parseFloat(num.toFixed(dec));
|
||||
}
|
||||
|
||||
var parts = num.toString().split(".");
|
||||
if (parts.length == 1 && dec == null) {
|
||||
// integer where we do not want to touch the decimals
|
||||
dec = 0;
|
||||
}
|
||||
|
||||
var integer = parts[0];
|
||||
if (tsep) {
|
||||
var thousands = /(-?[0-9]+)([0-9]{3})/;
|
||||
while(thousands.test(integer)) {
|
||||
integer = integer.replace(thousands, "$1" + tsep + "$2");
|
||||
}
|
||||
}
|
||||
|
||||
var str;
|
||||
if (dec == 0) {
|
||||
str = integer;
|
||||
} else {
|
||||
var rem = parts.length > 1 ? parts[1] : "0";
|
||||
if (dec != null) {
|
||||
rem = rem + new Array(dec - rem.length + 1).join("0");
|
||||
}
|
||||
str = integer + dsep + rem;
|
||||
}
|
||||
return str;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user