Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse float with 3 digits after comma?

Tags:

javascript

I have float number

var distance = 3.643462215;

I want the result to be like this:

my distance is 3 kilometers and 643 meters

like image 495
Alex Avatar asked Dec 02 '25 08:12

Alex


2 Answers

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"
like image 127
hsz Avatar answered Dec 04 '25 22:12

hsz


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

like image 40
nanobash Avatar answered Dec 04 '25 22:12

nanobash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!