Skip to content

Instantly share code, notes, and snippets.

@awps
Created August 9, 2022 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awps/3fcdf1857e33a94543a474ae124f74c6 to your computer and use it in GitHub Desktop.
Save awps/3fcdf1857e33a94543a474ae124f74c6 to your computer and use it in GitHub Desktop.
Pixel to Percent TypeScript/Javascript
export const pixelToPercent = (pixelNumber: number, containerSize: number) => {
const percent = 100 / containerSize * pixelNumber;
if (percent > 100) {
return 100;
} else if (percent < 0) {
return 0;
}
return Math.round((percent + Number.EPSILON) * 100) / 100;
};
@awps
Copy link
Author

awps commented Aug 9, 2022

pixelToPercent(150, 600); // 25
pixelToPercent(200, 600); // 33.333333
pixelToPercent(800, 600); // 100
pixelToPercent(-20, 600); // 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment