javascript中如何使浮点数保留固定的小数位数?

AdamsLee 2003-09-16 10:23:31
比如10/3得到的数字保留2为小数位数得3.33
...全文
1036 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
cloudchen 2003-09-16
  • 打赏
  • 举报
回复
加个判断

<SCRIPT LANGUAGE="JavaScript">
if(!Number.prototype.toFixed) {
Number.prototype.toFixed = function(n) {
with(Math) return round(Number(this)*pow(10,n))/pow(10,n)
}
}
alert(8.88888.toFixed(2))
</SCRIPT>
shyslysky 2003-09-16
  • 打赏
  • 举报
回复
<script language="JavaScript">

var test=10/3;
Number.prototype.fixed=function(n){
with(Math)return round(Number(this)*pow(10,n))/pow(10,n)
}
alert(test.fixed(2))
alert(test.toFixed(2))//ie5.5+

</script>
shyslysky 2003-09-16
  • 打赏
  • 举报
回复
<script>
var test=8.8888
Number.prototype.fixed=function(n){
with(Math)return round(Number(this)*pow(10,n))/pow(10,n)
}
alert(test.fixed(2))
alert(test.toFixed(2))//ie5.5+
</script>

87,988

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧