Formats number state with selected language in compute_state_display (#7516)

This commit is contained in:
Josh McCarty 2020-10-30 14:58:52 -07:00 committed by GitHub
parent 1d9779d47c
commit 14db37459f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 40 additions and 1 deletions

View File

@ -5,6 +5,7 @@ import { formatDateTime } from "../datetime/format_date_time";
import { formatTime } from "../datetime/format_time";
import { LocalizeFunc } from "../translations/localize";
import { computeStateDomain } from "./compute_state_domain";
import { numberFormat } from "../string/number-format";
export const computeStateDisplay = (
localize: LocalizeFunc,
@ -19,7 +20,9 @@ export const computeStateDisplay = (
}
if (stateObj.attributes.unit_of_measurement) {
return `${compareState} ${stateObj.attributes.unit_of_measurement}`;
return `${numberFormat(compareState, language)} ${
stateObj.attributes.unit_of_measurement
}`;
}
const domain = computeStateDomain(stateObj);

View File

@ -0,0 +1,22 @@
/**
* Formats a number based on the specified language with thousands separator(s) and decimal character for better legibility.
*
* @param num The number to format
* @param language The language to use when formatting the number
*/
export const numberFormat = (
num: string | number,
language: string
): string => {
// Polyfill for Number.isNaN, which is more reliable that the global isNaN()
Number.isNaN =
Number.isNaN ||
function isNaN(input) {
return typeof input === "number" && isNaN(input);
};
if (!Number.isNaN(Number(num)) && Intl) {
return new Intl.NumberFormat(language).format(Number(num));
}
return num.toString();
};

View File

@ -64,6 +64,20 @@ describe("computeStateDisplay", () => {
assert.strictEqual(computeStateDisplay(localize, stateObj, "en"), "123 m");
});
it("Localizes and formats numeric sensor value with units", () => {
const stateObj: any = {
entity_id: "sensor.test",
state: "1234.5",
attributes: {
unit_of_measurement: "m",
},
};
assert.strictEqual(
computeStateDisplay(localize, stateObj, "en"),
"1,234.5 m"
);
});
it("Localizes unknown sensor value with units", () => {
const altLocalize = (message, ...args) => {
if (message === "state.sensor.unknown") {