Show unit for number domains (#23101)

* Show unit for number domains

* Remove duplicated code

* Allow monetary formatting

Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>

* Update src/common/entity/compute_state_display.ts

---------

Co-authored-by: Petar Petrov <MindFreeze@users.noreply.github.com>
This commit is contained in:
Abílio Costa 2024-12-04 11:25:29 +00:00 committed by GitHub
parent 3c03dfb322
commit af1622e306
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 41 additions and 16 deletions

View File

@ -56,13 +56,15 @@ export const computeStateDisplayFromEntityAttributes = (
}
const domain = computeDomain(entityId);
const is_number_domain =
domain === "counter" || domain === "number" || domain === "input_number";
// Entities with a `unit_of_measurement` or `state_class` are numeric values and should use `formatNumber`
if (
isNumericFromAttributes(
attributes,
domain === "sensor" ? sensorNumericDeviceClasses : []
)
) ||
is_number_domain
) {
// state is duration
if (
@ -165,20 +167,6 @@ export const computeStateDisplayFromEntityAttributes = (
}
}
// `counter` `number` and `input_number` domains do not have a unit of measurement but should still use `formatNumber`
if (
domain === "counter" ||
domain === "number" ||
domain === "input_number"
) {
// Format as an integer if the value and step are integers
return formatNumber(
state,
locale,
getNumberFormatOptions({ state, attributes } as HassEntity, entity)
);
}
// state is a timestamp
if (
[

View File

@ -269,6 +269,43 @@ describe("computeStateDisplay", () => {
);
});
describe("Localizes a number entity value with translated unit_of_measurement", () => {
const testDomain = (domain: string) => {
const entity_id = `${domain}.test`;
const stateObj: any = {
entity_id: entity_id,
state: "1234",
attributes: {},
};
const entities: any = {
[entity_id]: {
translation_key: "custom_translation",
platform: "custom_integration",
},
};
assert.strictEqual(
computeStateDisplay(
localize,
stateObj,
localeData,
numericDeviceClasses,
demoConfig,
entities
),
`1,234 component.custom_integration.entity.${domain}.custom_translation.unit_of_measurement`
);
};
it("Localizes counter domain", () => {
testDomain("counter");
});
it("Localizes number domain", () => {
testDomain("number");
});
it("Localizes input_number domain", () => {
testDomain("input_number");
});
});
describe("Localizes input_datetime with full date time", () => {
const stateObj: any = {
entity_id: "input_datetime.test",