Menu

gitpiper

toOrdinalSuffix javascript Code Snippet in 2024

mathintermediate

Last Updated: 4 May 2024

Takes a number and returns it as a string with the correct ordinal indicator suffix.

  • Use the modulo operator (%) to find values of single and tens digits.
  • Find which ordinal pattern digits match.
  • If digit is found in teens pattern, use teens ordinal.
const toOrdinalSuffix = num => { const int = parseInt(num), digits = [int % 10, int % 100], ordinals = ['st', 'nd', 'rd', 'th'], oPattern = [1, 2, 3, 4], tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19]; return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) ? int + ordinals[digits[0] - 1] : int + ordinals[3]; };
toOrdinalSuffix('123'); // '123rd'

javascript snippet similar to toOrdinalSuffix For You in May 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️