【问题标题】:Data Saved as Strings, But need Ints数据保存为字符串,但需要整数
【发布时间】:2021-12-06 19:46:18
【问题描述】:

我正在从表中检索数据。数据是数字,但在mySql数据库中保存为TINYTEXT。我可以很好地检索它并访问它,但是我遇到了麻烦,因为我需要添加数字。

所以虽然我想要 4 + 5 + 3 = 12.... 而我得到的结果是“453”。

这是我对检索到的数据的计算:

let consultingScore = 0;
let consultingScoreDiv = 0;
   for (let i = 0; i < result.length; i++){
   let tempConScore = result[i].formValue01 + 
   result[i].formValue02 + result[i].formValue03;

   consultingScore = consultingScore + tempConScore;

   this.setState({ surveyScoreConsulting: consultingScore }); <--- (This should be 12, but is instead "453"
                }

我曾尝试像下面那样使用 parseInt(),但是当我这样做时,该值将变为 NaN。我没有正确使用 parseInt 吗?将字符串数字转换为整数似乎比这更容易,以便我可以使用它们进行计算。

let consultingScore = 0;
let consultingScoreDiv = 0;
   for (let i = 0; i < result.length; i++){
   let tempConScore = parseInt(result[i].formValue01) + 
   parseInt(result[i].formValue02) + parseInt(result[i].formValue03);

   consultingScore = consultingScore + tempConScore;

   this.setState({ surveyScoreConsulting: consultingScore }); <--- (This should be 12, but is instead "453"
                }

【问题讨论】:

标签: javascript mysql reactjs


【解决方案1】:

尝试以 10 为底进行解析,例如 parseInt(yourValue, 10)

【讨论】:

  • 我刚试过,它也给了我 NaN。
  • 您确定要解析的值吗?
  • 在上面那个人对我评论的文章中,它建议在变量中添加 + 作为前缀。我这样做了,现在它按预期工作。我以前从未听说过。
猜你喜欢
  • 2016-08-09
  • 2017-06-22
  • 2015-08-20
  • 2022-11-25
  • 2013-11-30
  • 2019-12-21
  • 2013-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多