简体   繁体   English

在反应计算器中修剪前导零

[英]Trim leading zeros in a react calculator

I'm learning react and for that purpose I'm implementing a react calculator, and I would like to remove the leading zeros, in order to show the number without these zeros, for example if I get a 07, in the display I have to show just the 7, but I have for example: 7+15+08, it's the same I have to show immediately 7+15+8.我正在学习反应,为此我正在实现一个反应计算器,我想删除前导零,以显示没有这些零的数字,例如,如果我得到一个 07,我有只显示 7,但我有例如:7+15+08,我必须立即显示 7+15+8。 I'm using react components:我正在使用反应组件:

handleClick = (e) => {
    let output = this.state.output;
    let value = e.target.textContent;
    //Im doing some validations for the numbers before.
    //If it is valid I'm updating the state of the display, carrying the output with the new 
    //value. for example output: 7+ and the new value: 0 the new state is gonna be 7+0
     if (!isInvalid) {
      this.setState({
        output: `${output}${value}`,
      });
}

I was thinking in validate every time I get a number, iterate over the new display value in reverse way until I find a character for example ('+','-','/','*') in this point I will have a string with the part of the last number in the operation.每次我得到一个数字时,我都在考虑验证,以相反的方式迭代新的显示值,直到我找到一个字符,例如('+','-','/','*')在这一点上我会有一个字符串,其中包含操作中最后一个数字的一部分。 For example if I have 6+07, after the iteration process I will have 70, the I must to reverse this string and finally cast this getting just the 7.例如,如果我有 6+07,在迭代过程之后我将有 70,我必须反转这个字符串并最终将其转换为 7。

But I'm thinking that it is not an elegant way to achieve this.但我认为这不是实现这一目标的优雅方式。 Is there a more sophisticated solution?有更复杂的解决方案吗?

I followed this tutorial to build the calculator.我按照本教程构建了计算器。 https://medium.com/@nitinpatel_20236/how-to-build-a-simple-calculator-application-with-react-js-bc10a4568bbd . https://medium.com/@nitinpatel_20236/how-to-build-a-simple-calculator-application-with-react-js-bc10a4568bbd

You could simply chain parseInt (or parseFloat ) with toString() .您可以简单地将parseInt (或parseFloat )与toString()链接起来。 This will remove leading zeros.这将删除前导零。

 const foo = "07" const bar = parseInt(foo, 10).toString() console.log(bar)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM