Reputation: 111
I am taking value in input but in result i want to add "+" 10% in the result i.e if a person inputs 1000 and the 10% of 1000 is 100 and the total result will be 1100. I am using "+" but it is concatenating the value istead of adding
function app() {
const [price, setPrice] = useState(0);
return (
<div>
<label>Price</label>
<input
type="number"
value={price}
onChange={e => setPrice(e.target.value)}
/>
<div>{price + (10 / 100) * price}</div>
</div>
);
}
How can i add these two values
Upvotes: 1
Views: 977
Reputation: 520
You can use parseInt for convert string to number in JavaScript. Problem in your script you are adding 2 values string and number.
function app() {
const [price, setPrice] = useState(0);
return (
<div>
<label>Price</label>
<input
type="number"
value={price}
onChange={e => setPrice(e.target.value)}
/>
<div>{(parseInt(price) + (10 / 100)) * parseInt(price)}</div>
</div>
);
}
Upvotes: 0
Reputation: 1643
All you have to do is to add a plus sign +
before e.target.value
to convert it to a number:
function app() {
const [price, setPrice] = useState(0);
return (
<div>
<label>Price</label>
<input type="number" value={price} onChange={(e) => setPrice(+e.target.value)} />
{price + (10 / 100) * price}
</div>
);
}
Upvotes: 0
Reputation: 1062
Use Number to avoid setting price as a String:
function app(){
const [price,setPrice]=useState(0);
return(
<div>
<label>Price</label>
<input
type='number'
value={price}
onChange={(e)=> setPrice(Number(e.target.value))}
</div>
{price + (10/100)*price}
/>
}
Beware of NaN though.
Upvotes: 1