#is there a better way to write this

22 messages · Page 1 of 1 (latest)

next veldt
#

(+(+cryptoPrices[0].priceUsd).toFixed(2)).toLocaleString()

priceUsd is a string

raven steeple
#

Write a function that does that. Use Number(...) instead of a + and parseFloat

#

perhaps it should accept something like (value: T extends { priceUsd: string}) instead of an array

tired violet
raven steeple
#

i'd go with something like

const roundTo2DecimalPlaces = (num: number): number =>
  Math.round(num * 100) / 100;

const formatCryptoPrice = (crypto: { priceUsd: string }): string =>
  roundTo2DecimalPlaces(parseFloat(crypto.priceUsd))
    .toLocaleString();
tired violet
#

that...

#

doesn't work

#

also roundTo2DecimalPlaces is way too specific

raven steeple
#

Number(cryptoPrices[0].priceUsd) could also return NaN so in both examples we need additional validation

#

And yes, i did not check the code, sorry about that

tired violet
next veldt
#

looks like it is working allthough i dont understand why we multiply by 100 and then divide by 100

tired violet
#

to keep the cents when rounding

next veldt
#

ah okay

#

i get it now

#

if i wanted 3 places then i needed 1000

tired violet
#

yeah

raven steeple
#

And if we are sure there is no such separators, we could expect a number instead of a string. Yet, values are string's

kindred jewel
#

You never want to use float to store data that you can accumulate. Always use integers that represent the smallest non-divisible unit (such as : cents )