mirror of
https://github.com/home-assistant/frontend.git
synced 2025-04-25 05:47:20 +00:00
Formats number state with selected language in compute_state_display (#7516)
This commit is contained in:
parent
1d9779d47c
commit
14db37459f
@ -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);
|
||||
|
22
src/common/string/number-format.ts
Normal file
22
src/common/string/number-format.ts
Normal 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();
|
||||
};
|
@ -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") {
|
||||
|
Loading…
x
Reference in New Issue
Block a user