我有浮点数
var distance = 3.643462215;
我希望结果如下:
我的距离是3公里和643米
答案 0 :(得分:7)
让我们假设distance
肯定是浮动的 - 如果它的字符串,请执行:distance = parseFloat(distance)
您可以尝试:
distance.toFixed(3);
给你3.643
;您可以使用以下命令将其拆分为分隔值:
distance.toFixed(3).split('.');
它返回:
["3", "643"]
所以让它运行:
var distance = 3.643462215,
parts = distance.toFixed(3).split('.'),
output = 'my distance is ' + parts[0] + ' kilometers and ' + parts[1] + ' meters';
输出:
"my distance is 3 kilometers and 643 meters"
答案 1 :(得分:4)
var distance = 3.643462215;
var reg = /(\d*)\.(\d{0,3})/; // using reg exp, because split won't work with float numbers
var res = reg.exec(distance);
console.log(res[1] + " Kilometers, " + res[2] + " Meters"); // 3 Kilometers, 643 Meters
在脚本中,我在RegExp
的帮助下(在.
之前及之后)将数字分成两部分,然后使用存储在res
变量
答案 2 :(得分:2)
var distance = 3.643462215;
var n = Math.floor(distance); // KM part
var m = Math.round((distance-n) * 1000); // meter part
答案 3 :(得分:1)
Math.round(distance * 1000) / 1000
答案 4 :(得分:0)
我能建议的最简单的解决方案是
<script type="text/javascript">
var distance = 3.643462215;
var strDistance = distance.toString();
var km = strDistance.substr(0, strDistance.indexOf('.'));
var mt = strDistance.substr(strDistance.indexOf('.')+1, 3);
alert("my distance is "+km+" kilometers and "+mt+" meters");
</script>