Jen
Jen

Reputation: 1733

Getting numbers after decimal in Javascript

I have a color picker, and the hue values returned are numbers between zero and 1. To create variations on the hue, I add .2 for 20%, .8 for 80% etc.

How can I keep the numbers going around the circle, so that when the number goes above 1, it subtracts the 1. How can I make this number into this number: 1.73540012511 ---> .7354

I tried using a "cents" javascript, (http://www.irt.org/script/6.htm) but this returned values greater than 1: http://jsfiddle.net/Se9Dn/

I can't use Math.min, because I want 1.2 to become .2 (not to have the colors all become red when they hit 1).

Thanks. :)


Edit: Confirming solution, with rounding added. Assuming you have an HSL color (Hue, Saturation, Luminosity) returned from Farbtastic and want to adjust Hue mathematically:

hslcolor  = (.73802938, .59832908, .948987);
colorStep = .2;
newcolor[0] = Math.round ( ((1*colorStep +hslcolor[0])%1)*10000 ) /10000;

Watch out those parenthesis are very tricky in there.

Upvotes: 1

Views: 424

Answers (2)

Sirko
Sirko

Reputation: 74036

You can use the modulo operator % (MDN docu).

So for adding, e.g., 0.8:

result = (result + 0.8) % 1;

EDIT

The modulo operator of JavaScript is actually more of a remainder operator.

Citing the ECMAScript spec Section 5.2:

The notation “x modulo y” (y must be finite and nonzero) computes a value k of the same sign as y (or zero) such that abs(k) < abs(y) and x−k = q × y for some integer q.

Upvotes: 5

Pointy
Pointy

Reputation: 413702

You just subtract the integer:

function cent(amount) { return (+amount) - Math.floor(+amount); }

If the number can be negative, then the it depends on the semantics you want. I'll leave that as an exercise :-)

Upvotes: 1

Related Questions