github.com/richardwilkes/toolbox@v1.121.0/txt/digits.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 "fmt" 14 "unicode" 15 16 "github.com/richardwilkes/toolbox/errs" 17 ) 18 19 // DigitToValue converts a unicode digit into a numeric value. 20 func DigitToValue(ch rune) (int, error) { 21 if ch < '\U00010000' { 22 r16 := uint16(ch) 23 for _, one := range unicode.Digit.R16 { 24 if one.Lo <= r16 && one.Hi >= r16 { 25 return int(r16 - one.Lo), nil 26 } 27 } 28 } else { 29 r32 := uint32(ch) 30 for _, one := range unicode.Digit.R32 { 31 if one.Lo <= r32 && one.Hi >= r32 { 32 return int(r32 - one.Lo), nil 33 } 34 } 35 } 36 return 0, errs.New(fmt.Sprintf("Not a digit: '%v'", ch)) 37 }