Skip to content

Commit

Permalink
Show unit for number domains (#23101)
Browse files Browse the repository at this point in the history
* Show unit for number domains

* Remove duplicated code

* Allow monetary formatting

Co-authored-by: Petar Petrov <[email protected]>

* Update src/common/entity/compute_state_display.ts

---------

Co-authored-by: Petar Petrov <[email protected]>
  • Loading branch information
abmantis and MindFreeze authored Dec 4, 2024
1 parent 3c03dfb commit af1622e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 16 deletions.
20 changes: 4 additions & 16 deletions src/common/entity/compute_state_display.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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 (
[
Expand Down
37 changes: 37 additions & 0 deletions test/common/entity/compute_state_display.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit af1622e

Please sign in to comment.