Bug 1029540 - ViewHelpers.L10N.numberWithDecimals doesn't properly handle NaN and numbers that can't be localized, r=bgrins

This commit is contained in:
Victor Porof 2014-06-24 21:45:52 -04:00
Родитель 285f9c80c1
Коммит f68a8d7ae4
3 изменённых файлов: 36 добавлений и 0 удалений

Просмотреть файл

@ -29,6 +29,7 @@ support-files =
[browser_graphs-14.js]
[browser_layoutHelpers.js]
[browser_layoutHelpers-getBoxQuads.js]
[browser_num-l10n.js]
[browser_observableobject.js]
[browser_outputparser.js]
[browser_prefs.js]

Просмотреть файл

@ -0,0 +1,25 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
// Tests that ViewHelpers.Prefs work properly.
let {ViewHelpers} = Cu.import("resource:///modules/devtools/ViewHelpers.jsm", {});
function test() {
let l10n = new ViewHelpers.L10N();
is(l10n.numberWithDecimals(1234.56789, 2), "1,234.56",
"The first number was properly localized.");
is(l10n.numberWithDecimals(0.0001, 2), "0",
"The second number was properly localized.");
is(l10n.numberWithDecimals(1.0001, 2), "1",
"The third number was properly localized.");
is(l10n.numberWithDecimals(NaN, 2), "0",
"NaN was properly localized.");
is(l10n.numberWithDecimals(null, 2), "0",
"`null` was properly localized.");
is(l10n.numberWithDecimals(undefined, 2), "0",
"`undefined` was properly localized.");
finish();
}

Просмотреть файл

@ -365,11 +365,21 @@ ViewHelpers.L10N.prototype = {
if (aNumber == (aNumber | 0)) {
return aNumber;
}
if (isNaN(aNumber) || aNumber == null) {
return "0";
}
// Remove {n} trailing decimals. Can't use toFixed(n) because
// toLocaleString converts the number to a string. Also can't use
// toLocaleString(, { maximumFractionDigits: n }) because it's not
// implemented on OS X (bug 368838). Gross.
let localized = aNumber.toLocaleString(); // localize
// If no grouping or decimal separators are available, bail out, because
// padding with zeros at the end of the string won't make sense anymore.
if (!localized.match(/[^\d]/)) {
return localized;
}
let padded = localized + new Array(aDecimals).join("0"); // pad with zeros
let match = padded.match("([^]*?\\d{" + aDecimals + "})\\d*$");
return match.pop();