1

how can i extract float value like (0.9) to be a whole integer value (9) in JavaScript?

example

var total = 67.9; 
something to process  var whole var DEC to be like 
var whole = 67;
var DEC = 9;
7
  • 1
    why 9 and not 0.9? what should happen with numbers, like 42.321? should it return dec = 321? Commented Nov 13, 2016 at 9:51
  • numbers like 42.321 should return 42 and 321 not 0.321 Commented Nov 13, 2016 at 10:00
  • In general case it's not possible (due to finite precision). There is a chance you're doing something in a wrong way and you better explain the original problem you're solving. Commented Nov 13, 2016 at 10:00
  • @zerkms It's not possible if you're working with numbers only (and yes, I tried out of curiosity - it almost never gives the right answer), but since this is a representation problem we might as well work with strings. Commented Nov 13, 2016 at 10:06
  • @MaxArt var total = 67.9; --- well, in the question they are dealing with numbers not strings. Since not every number is correctly representable - you cannot tell (in runtime) whether the numeric literal and its string representation are the same thing. Commented Nov 13, 2016 at 10:08

2 Answers 2

2

The simplest way I can think of is this:

var string = total.toString();
var dotidx = string.indexOf(".");
var dec = dotidx >= 0 ? +string.slice(dotidx + 1) : 0;

Notice that it doesn't work with numbers in exponential forms.

Sign up to request clarification or add additional context in comments.

Comments

2

There are many ways to find a result. I give you one simple solution.

var total = 67.9
var splitVal = total.toString().split(".")
var whole = splitVal[0], var desc = splitVal[1] || 0 

and if you want to convert whole and desc in number then multiply by 1.

var whole = splitVal[0] * 1

2 Comments

This would return undefined/NaN if total is actually an integer.
we can set var desc = splitVal[1] || 0. Thanks MaxArt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.