user13286
user13286

Reputation: 3075

Convert integer to string, split at the decimal and then include the decimal in the 2nd part of the array?

I would like to split a number at the decimal in order to convert the number after the decimal into a fraction.

var num = 2.2287,
    numString = num.toString(),
    numSplit = numString.split('.'),
    decimal = parseInt(numSplit[1]);

$('.number').text(decimal);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="number"></div>

This gets me 2287, how would I go about adding the decimal back into the 2nd part of the array so that I would get .2287

Upvotes: 0

Views: 530

Answers (4)

dylzee
dylzee

Reputation: 421

var num = 2.2287;
let numString = num.toString();
$('.number').text(numString.slice(numString.indexOf('.'), -1));

If the return needs to be an int, then the best solution might be to simply add the period in a template literal.

var num = 2.2287,
    numString = num.toString(),
    numSplit = numString.split('.'),
    decimal = parseInt(numSplit[1]);

$('.number').text(`.${decimal}`);

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

One way, explanatory comments in the code:

// initial number-value:
let num = 2.2287,
    // retrieving the integer portion:
    integer = parseInt(num, 10),
    // retrieving the decimal portion by subtracting
    // the previous integer from the initial num:
    decimal = num - integer,
    // rounding to four decimal places,
    // first multiplying the decimal by 10000
    // using Math.round() to round to an integer,
    // and then dividing by 10000 to convert it
    // back to a float:
    rounded = Math.round(decimal*10000)/10000;

$('.number').text(rounded});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="number"></div>

As an alternative:

// initial number-value:
let num = 2.2287,
    // using a destructuring assignment to assign
    // the zeroth array-element as the integer,
    // and the second as the decimal after
    // we convert the number to a String, and
    // then call String.prototype.split():
    [integer, decimal] = num.toString().split('.');

// here we use a template-literal String to
// interpolate the decimal variable into
// the String following the initial '.'
// character:
$('.number').text(`.${decimal}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="number"></div>

References:

Upvotes: 1

J. Mac
J. Mac

Reputation: 221

Alternatively, you can use substring to get the decimal and everything that follows.

var num = 2.2287,
    numString = num.toString(),
    decimal = parseFloat(numString.substring(numString.indexOf('.')))

Upvotes: 1

Kirill Savik
Kirill Savik

Reputation: 1278

Please use concat() function.

$('.number').text(".".concat(decimal));

Upvotes: 1

Related Questions