#is there a better way to write this
22 messages · Page 1 of 1 (latest)
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
(Math.round(Number(cryptoPrices[0].priceUsd) * 100) / 100).toLocaleString() maybe
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();
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
it could but even if it does i don't think it really needs to be handled
hmm let me try
looks like it is working allthough i dont understand why we multiply by 100 and then divide by 100
to keep the cents when rounding
yeah
Well, in some languages it is common to use a , as a separator but even a . will kill it
Since the values are strings, there should be a validation.
And if we are sure there is no such separators, we could expect a number instead of a string. Yet, values are string's
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 )