-1

is it possible to get the decimal places only and convert it to whole number??

var Decimal = 1.25;

i want to get only the .25 and convert it to whole number so it will be like

25

is that possible??

I tried searching on the net it seems that i cant any answer to my question so i tried to ask here

i just need to get the decimal places and convert it to whole number again basically make it an int data type

any idea on how to solve my problem?

bRaNdOn
  • 1,060
  • 4
  • 17
  • 37

1 Answers1

2

Probably the simplest way is to go through text:

var value = 1.25;
var fractionalPartAsWholeNumber = +String(value).split(".")[1];

That's fairly dense, but basically:

  • String(value) gives us a string "1.25"
  • .split(".") gives us an array with "1" in the first entry and "25" in the second
  • [1] accesses the second entry in the array
  • The + at the very beginning converts that back to a number — assuming you want it as a number, that is; if you want it as a string, leave that leading + off

If the values always have two digits of precision, you can do it mathematically:

var value = 1.25;
var fractionalPartAsWholeNumber = (value - Math.floor(value)) * 100;

Or you could convert to string, find out how many places there are to the right of the ., and then do the above but multiplying by 10^places. But the string method is probably fine.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875