In my app, I want to let the user update an old amount. For example, if the amount was 2.00 and the user adds .50 cents it should read 2.50 when the user hits the total button, but I am getting 2.5
instead, where the zero is stripped off by the parsFloat
. I tried toFixed(2)
:
setTotal(parseFloat(balance).toFixed(2) +
parseFloat(newBalance).toFixed(2);
but it is not working, I get 2.505
for example, not 2.50
. I am trying to write a function that will add the zeros after checking if the total has a decimal in it. I have multiple functions to add or subtract, so I need the function to work for all, in the below example I have only one function. Any help is much appreciated.
Here is the simplifiled code:
const AddForm = () => {
const [newBalance, setNewBalance] = useState("");
const [total, setTotal] = useState("");
const { id } = useParams();
const history = useHistory();
const addBalHandler = (e) => {
e.preventDefault();
axios({
method: "PUT",
url: `http://localhost:5000/update-snapshot/${id}`,
data: {
date: startDate,
},
}).then((res) => {
history.push(`/success/` + id )
console.log(res.data);
});
};
const addBal = () => {
const hasDecimal = total.includes(".")
if ( hasDecimal ) {
// condition to add the zeros at right of decimal
}
setTotal(parseFloat(balance) +
parseFloat(newBalance));
};
return (
<form
action="/update-snapshot/:id"
method="post"
onSubmit={addBalHandler}
>
<Col>
<Form.Label>Balance: </Form.Label>
<Input
setInputValue={setNewBalance}
inputValue={newBalance}
inputName={"newBalance"}
inputType={"text"}
/>
</Col>
<Col>
<Input
setInputValue={setTotal}
inputValue={total}
inputName={"total"}
inputType={"text"}
/>
<Button
onClick={() => {
state.addToBalChecked && addBal();
}}
>
Calculate Total
</Button>
</Col>
<div>
<Button type="submit">
Save
</Button>
</div>
</form>
);
};
export default AddForm;