JavaScript 将浮点数显示为小数点后 2 位 [英] JavaScript displaying a float to 2 decimal places

查看:24
本文介绍了JavaScript 将浮点数显示为小数点后 2 位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个数字显示到小数点后 2 位.

I wanted to display a number to 2 decimal places.

我想我可以在 JavaScript 中使用 toPrecision(2) .

I thought I could use toPrecision(2) in JavaScript .

但是,如果数字是 0.05,我会得到 0.0500.我宁愿它保持不变.

However, if the number is 0.05, I get 0.0500. I'd rather it stay the same.

JSbin 上查看.

最好的方法是什么?

我可以考虑编写一些解决方案,但我想(我希望)这样的东西是内置的?

I can think of coding a few solutions, but I'd imagine (I hope) something like this is built in?

推荐答案

float_num.toFixed(2);

注意:toFixed() 将在必要时用零进行舍入或填充以满足指定的长度.

Note:toFixed() will round or pad with zeros if necessary to meet the specified length.

这篇关于JavaScript 将浮点数显示为小数点后 2 位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆