color: Rounding errors with Color.hsl().string()

Certain colors (I’ve only seen this in HSL so far) don’t round correctly when calling string().

For example:

var Color = require('color');

var pink = Color('#FF08C2');
console.log(pink.hsl().string()); // 'hsl(314.79999999999995, 100%, 51.6%)'

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Reactions: 2
  • Comments: 15 (5 by maintainers)

Commits related to this issue

Most upvoted comments

The bug is that the library is taking a floating point number, using toFixed() to convert it to a rounded number in string form, then immediately converting back into a floating point number again.

		return new Color(this.color.map(roundToPlace(places)).concat(this.valpha), this.model);

and

let self = this.model in colorString.to ? this : this.rgb();
self = self.round(typeof places === 'number' ? places : 1);
const args = self.valpha === 1 ? self.color : self.color.concat(this.valpha);
return colorString.to[self.model](args);

The rounding needs to happen at the last minute when the result is passed back to the caller of .string() or .hex() etc.

(Nothing to do with the IEEE.)

Possibly related. Alpha value don’t seem to get rounded

rgba(47, 64, 85, 0.0784313725490196) hsla(213, 29%, 26%, 0.0784313725490196)

I agree that my input values might be a bit weird but the figma API is returning them unrounded as well.

Observed when using RGBA color('#000').fade(0.9).string(); returns "rgba(0, 0, 0, 0.09999999999999998)"

Have their been any decisions made on this issue? Still occurring in 3.1.3

@henopied Aware it’s a rounding problem. I thought it was fixed in color-string, though. Let me investigate.