I have float number
var distance = 3.643462215;
I want the result to be like this:
my distance is 3 kilometers and 643 meters
Lets assume that distance is for sure float - if it's string, do: distance = parseFloat(distance)
You can try with:
distance.toFixed(3);
which gives you 3.643; You can split it to separated values with:
distance.toFixed(3).split('.');
It returns:
["3", "643"]
So get it run:
var distance = 3.643462215,
parts = distance.toFixed(3).split('.'),
output = 'my distance is ' + parts[0] + ' kilometers and ' + parts[1] + ' meters';
Output:
"my distance is 3 kilometers and 643 meters"
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
In script I'm splitting number in two pieces with help of RegExp ( before . and after it ) and then manipulating with result which is stored in res variable
JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With