比如
var a=1.566;
格式换后为1.57
var a=1.56;
格式换后为1.56
var a=1234.566;
格式换后为1,234.57
var a=1234567.56;
格式换后为1,234,567.56
var a=0;
格式换后为0.00
可否用简便的js实现 求大神指导
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>menu</title>
<style type="text/css">
</style>
<script type="text/javascript">
function format (num, fixed)
{
return num.toFixed (fixed).replace (/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}
console.log (format (1.566, 2));
console.info (format (1.56, 2));
console.error (format (1234.566, 2));
console.debug (format (1234567.56, 2));
console.warn (format (0, 2));
</script>
</head>
<body>
</body>
</html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>menu</title>
<style type="text/css">
</style>
<script type="text/javascript">
function format (num, fixed)
{
return num.toFixed (fixed).replace (/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}
console.log (format (1.566, 2));
console.info (format (1.56, 2));
console.error (format (1234.566, 2));
console.debug (format (1234567.56, 2));
console.warn (format (0, 2));
</script>
</head>
<body>
</body>
</html>
温馨提示:答案为网友推荐,仅供参考