2014-03-19 89 views

回答

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
Math.round(distance * 1000)/1000 
+0

OP要word.please仔細閱讀問題 – Amit

+1

這有時不起作用,例如http://jsfiddle.net/Zk9x8/ – Huangism

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可變

JSFiddle

+0

要跳過'substr',你可以使用下面的正則表達式:'/(\ d *)\。(\ d {0,3})/' – hsz

+0

@hsz是的,對,我突然想到了:) – tnanoba

2
var distance = 3.643462215; 

var n = Math.floor(distance); // KM part 

var m = Math.round((distance-n) * 1000); // meter part 
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> 
+0

這不是最簡單的解決方案! – tnanoba

相關問題