Reputation: 136
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
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);
Xotic750's answer is better as it's slightly speedier: Example
Upvotes: 0
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
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
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
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