简体   繁体   中英

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.

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

So for adding, eg, 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.

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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM