Home > Software design >  React compound interest calculator Math.pow giving NaN?
React compound interest calculator Math.pow giving NaN?

Time:10-16

i'm just trying to make compound interest cal with react js but its giving me NaN as result im getting all thing but when i consolo.log Math.pow((1 interest / time, time * years)) its giving me NaN please help.

const CompoundInterest = () => {
  const [principal, setPrincipal] = useState();
  const [years, setYears] = useState();
  const [interest, setInterest] = useState();
  const [time, setTime] = React.useState("");
  const [result, setResult] = useState();

  const calculate = () => {
    // A=p(1 (r/n))^(nt)
    const amount = principal * Math.pow((1   interest / time, time * years));
    console.log((1   interest / time, time * years));
    const result = amount - principal;

    setResult(result.toFixed(2));
  };
  const handleChange = (e) => {
    setTime(e.target.value);
  };
  return (
    <>
      <div className="annualCompoundCalculator">
        <form>
          <TextField
            label="What is the principal?"
            variant="outlined"
            type="number"
            onChange={(e) => setPrincipal(e.target.value)}
          />
          <TextField
            label="How many years?"
            variant="outlined"
            type="number"
            onChange={(e) => setYears(e.target.value)}
          />
          <TextField
            label="Annual Interest rate?"
            variant="outlined"
            type="number"
            onChange={(e) => setInterest(e.target.value / 100)}
          />
          <InputLabel id="demo-simple-select-label">time</InputLabel>
          <Select
            labelId="demo-simple-select-label"
            id="demo-simple-select"
            value={time}
            label="Age"
            onChange={handleChange}
          >
            <MenuItem value={12}>Per Month</MenuItem>
            <MenuItem value={4}>Per 3 Month</MenuItem>
            {/* <MenuItem value={6}>Per 6 Month</MenuItem> */}
            <MenuItem value={1}>Per Year</MenuItem>
          </Select>

CodePudding user response:

in your calculate function

change time to Number(time)

CodePudding user response:

The reason must be that one of the three variables interest time years is null when you try to do the calculation, so the calculation returns NaN because they are not numbers

CodePudding user response:

  const calculate = () => {
    // A=p(1 (r/n))^(nt)
    const a = interest / time;
    const b = 1   a;
    const c = time * years;
    const d = Math.pow(b, c);
    const amount = (principal * d).toFixed(2);
    const result = amount;

    setResult(result);
  };

CodePudding user response:

[![enter image description here][1]][1]

here is the all value [1]: https://i.stack.imgur.com/tEqSa.png

  • Related