Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert Full-width number characters to Ascii in Golang?

Tags:

unicode

go

How do I convert full width characters into ascii characters in golang. The input in my program is full width numbers and I need to run some computations on them, so I assume I have to write a convert function like below, Before I start mapping bytes and such I was wondering if this is indeed available in the standard go library

fullWidth:="123"
expected := "123"
func convert(input string) string {
// body
}

expected == convert(fullWidth)
like image 296
aarti Avatar asked Dec 08 '25 14:12

aarti


1 Answers

You can use the width.Transformer of the golang.org/x/text package to do the transformation but the standard library does not have this functionality. x/text is one of many official sub-repositories which have weaker compatibility requirements (see here).

Example:

package main

import (
    "fmt"
    "golang.org/x/text/width"
)

func main() {
    s := "123"
    n := width.Narrow.String(s)
    fmt.Printf("%U: %s\n", []rune(s), s)
    fmt.Printf("%U: %s\n", []rune(n), n)
}
like image 52
nemo Avatar answered Dec 12 '25 04:12

nemo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!