vm7488
vm7488

Reputation: 136

How do you separate a javaScript variable's Whole number and it's decimal to style them separately?

If a non-whole number (decimal) integer is on a JS variable, what would you do to separate number and decimal so you can style them separately in CSS? Is there a magic JQuery/plugin/Library for that?

http://jsfiddle.net/vm7488/1ggbow5b/

(you can tell that a well-designed JSFiddle is seriously begging for an answer here)

Currently, push comes to shove - I'm planning to do a var modulus 1 not-equal to zero ( varia % 1 != 0 ) conditional and workout something from that, but if there was something, something like a already-made, built in function to do that, that would be awesome help, thanks!

Upvotes: 0

Views: 3506

Answers (5)

Jamie Barker
Jamie Barker

Reputation: 8256

You don't even need to do any Math really, you could just use RegEx to split the pence from the pound:

var RegEx = /([\d]+?)\.([\d]+)/g;
var Price = '25.50';
var StyledPrice = Price.replace(RegEx, '<div class="pound">$1</div><div class="dot">.</div><div class="pence">$2</div>');
$('div').html(StyledPrice);

EXAMPLE

UPDATE

Xotic750's answer is better as it's slightly speedier: Example

Upvotes: 0

Raja Ganesh
Raja Ganesh

Reputation: 1

In case of handling it as a number.

var value= 25.50;

var integer = Math.floor ( value) ; // = 25 var decimal = value - integer ; // = .50

Also incase of strings

var numbers= value.toString().split('.');

then you can perform casting on the array index positions. Like,

integer = parseInt(number[0]); fraction = parseInt(number[1]);

Upvotes: 0

abhiklpm
abhiklpm

Reputation: 1653

Check out the updated version of your fiddle:

http://jsfiddle.net/abhiklpm/1ggbow5b/2/

function hey() {
    //generate 25.50 and simply display it.
    this.num = 25.50;
    var parts = this.num.toString().split('.');
    this.whole = parts[0];
    this.dec = Number("."+parts[1]).toFixed(2).replace('0','');  
    this.num = this.whole + this.dec;
}

Updated fiddle with comments : http://jsfiddle.net/abhiklpm/1ggbow5b/4/

Upvotes: 2

Xotic750
Xotic750

Reputation: 23492

Keeping it really simple like @TrueBlueAussie suggested.

var out = document.getElementById('out'),
    text = '25.50',
    parts = text.split('.');

out.textContent = 'Integer part: ' + parts[0] + '\nDecimal part: ' + (parts[1] || 0);
<pre id="out"></pre>

Upvotes: 1

meskobalazs
meskobalazs

Reputation: 16041

You can just simple separate it by using Math.floor():

var integerPart = Math.floor(varia);
var fraction = varia - integerPart;

Then format these as you wish.

If you also need negatives, you should use Math.ceil() in that case, so like this:

if (varia < 0) {
    var integerPart = Math.ceil(varia);
    var fraction = varia - integerPart; 
} else {
    // same as above
}

Upvotes: 4

Related Questions