H
H
hitakiri2016-11-30 14:33:56
go
hitakiri, 2016-11-30 14:33:56

How to write a number as a fraction in Go?

Good time.
It is necessary to store a fraction record in variables, for example 1/4, not 0.25.
Those. something like :

//Естественно это не работает!!! Код вставил для примера

var ch1 float64
ch1 = 1 / 4
fmt.Println(ch1)

//--------------
0.25

Perhaps someone faced a similar problem.
Thank you in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Shevelev, 2016-12-03
@mantyr

Make a structure, pass text to it, then make a package out of it and add methods for managing, converting, and so on...

package main

import (
  "fmt"
  "strings"
  "errors"
)

func main() {
  fmt.Println("Hello, playground")
  
  d := New()
  d.Parse("1/4")
  fmt.Println(d)
}

type Shot struct {
  i string                   // number
  f string                   // fraction
}

func New() (s *Shot) {
  s = new(Shot)
  return
}

func (s *Shot) Parse(text string) (err error) {
  v := strings.Split(text, "/")
  if len(v) != 2 {
    err = errors.New("Error parse shot")
    return	
  }
  s.i = v[0]
  s.f = v[1]
  return
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question