最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】js中float浮点数转换为百分比后保留1位小数再转换为字符串

JS crifan 1189浏览 0评论
js中,需要把:
        memberInfo : {
          'username': 'Maggie',
          'totalScriptCount': 121,
          'publishedScriptCount': 100,
          'publishedScriptRatio': 
0.82644
,
          "unpublishedScriptCount": 0,
          'unpublishedScriptRatio': 0.173553,
        },
中的
0.82644
0.173553
变成:
“82.6”
“17.4”
js float to string format
How to format a float in javascript? – Stack Overflow
JavaScript toFixed() Method
formatting – Convert javaScript floating point numbers to string without loosing insignificant trailing zeros – Stack Overflow
JavaScript Number toString() Method
Number.prototype.toFixed() – JavaScript | MDN
Number.prototype.toPrecision() – JavaScript | MDN
const percentValue = text * 100
console.log("percentValue=", percentValue)
const oneDigitValueStr = percentValue.toPrecision(1)
console.log("oneDigitValueStr=", oneDigitValueStr)
return `${oneDigitValueStr}%`
竟然输出:
percentValue= 82.64
AllUserScriptCount.js:77 oneDigitValueStr= 8e+1
AllUserScriptCount.js:75 percentValue= 17.349999999999998
AllUserScriptCount.js:77 oneDigitValueStr= 2e+1
【总结】
换用代码:
const percentValue = text * 100
console.log("percentValue=", percentValue)
// const oneDigitValueStr = percentValue.toPrecision(1)
const oneDigitValue = percentValue.toFixed(1)
console.log("oneDigitValue=", oneDigitValue)
return `${oneDigitValue}%`
结果对了:
percentValue= 82.64
AllUserScriptCount.js:78 oneDigitValue= 82.6
AllUserScriptCount.js:73 text=0.1735, ...
AllUserScriptCount.js:75 percentValue= 17.349999999999998
AllUserScriptCount.js:78 oneDigitValue= 17.3
显示也对了:

转载请注明:在路上 » 【已解决】js中float浮点数转换为百分比后保留1位小数再转换为字符串

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.178 seconds, using 22.02MB memory