Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: 1.75 -> 1-3/4



On Tue, Jun 05, 2018 at 12:09:20AM +0200, Emanuel Berg wrote:
> Is this [1] the correct algorithm/a good
> implementation? It translates 1.75 into 1-3/4
> at least :P

What comes to mind first for me is the following.

- Matthew Martin

ths() {
	local decmal
	local -i denom num whole

	if [[ $1 != *.* ]]; then
		print -- $1
		return
	fi

	whole=${1%.*}
	decimal=${1#*.}
	num=$decimal
	denom=$(( 10 ** ${#decimal} ))

	for d in 2 5; do
		while (( num % d == 0 && denom % d == 0 )); do
			(( num /= d ))
			(( denom /= d ))
		done
	done

	(( whole )) && print -n -- $whole 
	(( whole && num )) && print -n ' '
	(( num )) && print -n -- $num/$denom
	print
}



Messages sorted by: Reverse Date, Date, Thread, Author