我的react组件中有两个变量。我想将一个变量与另一个变量相除,并仅将该值打印一位小数。因此,我选择了substring方法,如下所示:

 <div className="col-md-8">
      {(total_star / total_user).substring(0,2)}
 </div>


在输出中,出现以下错误:

TypeError: (total_star / total_user).substring is not a function



请帮助在jsx中打印子字符串。

最佳答案

那是因为结果是float而不是string,所以可以使用.toFixed(...)代替substring

(total_star / total_user).toFixed(2);


或将结果转换为string并使用.substring(...)

(total_star / total_user).toString().substring(0,2)


第一个示例可能不会为您提供所需的结果,因为.substring(0, 2)将为您提供前两个字符,而.toFixed(2)将为您提供结果,并在小数点后保留两位小数。

09-16 16:56