Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/common/entity/compute_state_display.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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);
Expand Down
22 changes: 22 additions & 0 deletions src/common/string/number-format.ts
Original file line number Diff line number Diff line change
@@ -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();
};
14 changes: 14 additions & 0 deletions test-mocha/common/entity/compute_state_display.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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") {
Expand Down