Javascript - Định dạng một số tới các vị trí thập phân
Định dạng một số tới các vị trí thập phân
Viết một hàm JavaScript để định dạng một số tới các vị trí thập phân
Ví dụ:
Mã nguồn:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script>
function decimals(n, d) {
if ((typeof n !== 'number') || (typeof d !== 'number'))
return false;
n = parseFloat(n) || 0;
return n.toFixed(d);
}
document.write(decimals(2.100212, 2)+"<br/>");
document.write(decimals(2.100212, 3)+"<br/>");
document.write(decimals(2100, 2)+"<br/>");
</script>
</head>
<body>
</body>
</html>
Lưu đồ thuật toán: