Search code examples
javascriptreact-nativeparsefloat

React native operation btw 2 floats


I want to do the subtraction between 2 floats. Everything works only when I enter a "," in my input to make a subtraction between 2 floats, I get NaN (Not a Number). Only I don't really understand how this is possible ^^ I tried several things like parseFloat in case they are strings or Number.

If someone could explain me?

There is my code:

const [alertPrice, setAlertPrice] = useState(0.0);

return (
  <>
    <TextInput
      style={styles.input}
      placeholderTextColor="#fff"
      keyboardType="numeric"
      maxLength={5}
      onChangeText={(text) => {
        props.handleChange("targetPrice", text);
        setAlertPrice(text);
      }}
      value={alertPrice}
    />
    <Text
      style={{
        left: width * 0.35,
        bottom: height * 0.02,
        color: "grey",
      }}
    >
      Economiser{" "}
      {item.actual_price && alertPrice
        ? (console.log(
            "calcul: ",
            Number(item.actual_price - alertPrice).toFixed(2)
          ),
          parseFloat(item.actual_price) - parseFloat(alertPrice)).toFixed(2)
        : "N/A"}{" "}
      €
    </Text>
  </>
);

Thanks you in advance guys !


Solution

  • Since your Operation works with "." but does not work with "," I would suggest looking into the Javascript Replace Function. It is pretty straight forward and the Docs can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace?retiredLocale=de

    ~ Faded