parseFloat turns thousands into single digit — unexpectedly Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of parseFloat turns thousands into single digit — unexpectedly without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a weird situation going on.

I have an array of objects… each object has a .value.rate field, and I am adding them all together.

For Example, let quoteSelections = ["$4,000", "$0.00"]

To do this, I am using the useEffect hook in react – each time the rate changes, it adds it up. The problem is, anything larger than a number with a hundreds placement revers back to single digits – so “4000” becomes the number 4.

  useEffect(() => {
    if (quoteSelections.length > 0) {
      let rateTotal = quoteSelections
        .map((selec) => parseFloat(selec.value.rate.slice(1)))
        .reduce((a, b) => a + b);
      if (rateTotal > 0) {
      } else {
  }, [quoteSelections]);

If quoteSelections = ["$400", "$0.00"] It works fine. But anything above 999 causes it to revert back to single digits.


It’s because of the comma in your strings, parseFloat does not know how to handle this, see documentation:

If parseFloat encounters a character other than a plus sign (+), minus sign (- U+002D HYPHEN-MINUS), numeral (0–9), decimal point (.), or exponent (e or E), it returns the value up to that character, ignoring the invalid character and characters following it.

I’m assuming your working input does not contain the dollar sign, because that would also cause it to not work.

We are here to answer your question about parseFloat turns thousands into single digit — unexpectedly - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji