Skip to content Skip to sidebar Skip to footer

Increment Float In React, String Conversion, State Representation

Here is the critical logic of my codebase: addLogicToEquation(newLogic) { let equation = this.state.equation console.log(parseFloat(equation)) if(newLogic==='10%'){

Solution 1:

Try this. The key difference for my code is I use type coercion to ensure the numbers are strings and concated. Also, I have a different set of logic for your percentage. It doesn't really need to be a huge conditional. Also, I have renamed variables. Your variable names are really deceptive. You're create new calculation values, not equations

addLogicToEquation(newLogic) {
  let newValue, multiplier
  let equation = this.state.equationif (newLogic.includes("%")) {
    multiplier = parseFloat(newLogic.replace("%","")) / 100.0
    newValue = parseFloat(equation) + parseFloat(equation) * multiplier 
  } else {
    newValue = parseFloat('' + parseFloat(equation) + newLogic)
  }
  this.setState({equation: newValue.toFixed(2)})
}

Solution 2:

Actually, the problem is when you enter second 6 you concatenate "6.00" string value to "6". So it becomes "6.006" and toFixed(2) round it to 6.01. To avoid this remove ".00" part when you concatenate.

let newEquation = Number(equation) + newLogic;

Post a Comment for "Increment Float In React, String Conversion, State Representation"