github.com/richardwilkes/toolbox@v1.121.0/txt/roman.go (about)

     1  // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, version 2.0. If a copy of the MPL was not distributed with
     5  // this file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  //
     7  // This Source Code Form is "Incompatible With Secondary Licenses", as
     8  // defined by the Mozilla Public License, version 2.0.
     9  
    10  package txt
    11  
    12  import (
    13  	"strings"
    14  )
    15  
    16  var (
    17  	romanValues = []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
    18  	romanText   = []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}
    19  )
    20  
    21  // RomanNumerals converts a number into roman numerals.
    22  func RomanNumerals(value int) string {
    23  	var buffer strings.Builder
    24  	for value > 0 {
    25  		for i, v := range romanValues {
    26  			if value >= v {
    27  				buffer.WriteString(romanText[i])
    28  				value -= v
    29  				break
    30  			}
    31  		}
    32  	}
    33  	return buffer.String()
    34  }