import { HassEntity } from "home-assistant-js-websocket" ; import { FrontendLocaleData , NumberFormat } from "./types" ; param stateObj export const isNumericState = ( stateObj ) : boolean => ! ! stateObj . attributes . unit_of_measurement || ! ! stateObj . attributes . state_class ; export const numberFormatToLocale = ( localeOptions ) : string | string [ ] | undefined => { switch ( localeOptions . number_format ) { case NumberFormat . comma_decimal : return [ "en-US" , "en" ] ; case NumberFormat . decimal_comma : return [ "de" , "es" , "it" ] ; case NumberFormat . space_comma : return [ "fr" , "sv" , "cs" ] ; case NumberFormat . system : return undefined ; default : return localeOptions . language ; } } ; export const round = ( value , precision = 2 ) : number => Math . round ( value * 10 ** precision ) / 10 ** precision ; param num param locale param options export const formatNumber = ( num , localeOptions ? , options ? ) : string => { const locale = localeOptions ? numberFormatToLocale ( localeOptions ) : undefined ; Number . isNaN = Number . isNaN || function isNaN ( input ) { return typeof input === "number" && isNaN ( input ) ; } ; if ( localeOptions ?. number_format !== NumberFormat . none && ! Number . isNaN ( Number ( num ) ) && Intl ) { try { return new Intl . NumberFormat ( locale , getDefaultFormatOptions ( num , options ) ) . format ( Number ( num ) ) ; } catch ( err ) { console . error ( err ) ; return new Intl . NumberFormat ( undefined , getDefaultFormatOptions ( num , options ) ) . format ( Number ( num ) ) ; } } if ( typeof num === "string" ) { return num ; } return `${ round ( num , options ?. maximumFractionDigits ) . toString ( ) }${ options ?. style === "currency" ? ` ${ options . currency }` : "" }` ; } ; param num param options const getDefaultFormatOptions = ( num , options ? ) : Intl . NumberFormatOptions => { const defaultOptions = { maximumFractionDigits : 2 , ... options , } ; if ( typeof num !== "string" ) { return defaultOptions ; } if ( ! options || ( ! options . minimumFractionDigits && ! options . maximumFractionDigits ) ) { const digits = num . indexOf ( "." ) > - 1 ? num . split ( "." ) [ 1 ] . length : 0 ; defaultOptions . minimumFractionDigits = digits ; defaultOptions . maximumFractionDigits = digits ; } return defaultOptions ; } ;