什么是RegEx才能输出以下结果:-
d = 1000 / 280;
console.log(d);
输出:
3.5714285714285716
但是我只想输出包括点在内的前3位数字。 (或者可以带点四个字符) 例如:-
3.57
更新:可以使用Math.floor
解决此问题
例如
d = 1000 / 280;
d = Math.floor(d * 100) / 100;
但是我实际上正在寻找一个基于正则表达式的解决方案。
答案 0 :(得分:1)
为什么需要正则表达式?
只需使用\t
:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js "> </script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
</head>
<body>
<table id="example" class="display" >
<thead>
<tr>
<th>name</th>
<th>position</th>
<th>office</th>
<th>age</th>
<th> date </th>
</tr>
</thead>
<tbody>
{% for i in qs %}
<tr>
<td>{{ i.name }}</td>
<td>{{ i.position }}</td>
<td>{{ i.office }}</td>
<td>{{ i.age }}</td>
<td> {{ i.date }} </td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
如果您仍想使用正则表达式进行操作,这就是您要查找的内容(该方法适用于任何数字,包括负数):
Math.floor
答案 1 :(得分:0)
您可能应该在这里使用Math.round
var d = 1000 / 280;
d = Math.round(d * 100) / 100;
console.log(d);
如果您真的想要正则表达式解决方案,则为:
var d = 1000 / 280;
output = (d+"").replace(/^(\d+\.\d{2}).*$/, "$1");
console.log(output);
我使用的正则表达式方法是先将十进制数转换为字符串。然后,捕获小数点前的数字和小数点后的两个数字,仅替换为该捕获的数字。
答案 2 :(得分:0)
您可以使用toFixed
函数
喜欢:
var num = 2.475467899;
num.toFixed(2);
那将返回 2.47
{toFixed(2)
,这里2
是您要求的小数点位数。