Home > Blockchain >  The .round(precission) Ruby method is not working
The .round(precission) Ruby method is not working

Time:12-26

Problems Detail:

My routine is a simple set of equations, the result must yield the result as an array of float elements with a precission of 4 decimals. The problem is that the .round(4) method is not working.

What I tried:

  1. Used .round(4)
  2. Used .to_f(4)

My code is as follows:

`

def bar_triang(p1,p2,p3)
  #your code here
  
  bary=[]
  
  x0= [p1[0],p2[0],p3[0]].sum 
  x0t= x0.div(3)
  x0tf = x0t.round(4)
  
  bary=bary.push(x0tf)
  
  y0 = [p1[1],p2[1],p3[1]].sum
  y0t =y0.div(3)
  y0tf = y0t.round(4)
  
  bary=bary.push(y0tf)
  
  p bary  
  
end

`

Note: The routine accepts an array of the following shape [p1,p2,p3] in which p1 to p3 are coordinates [x,y]. [p1,p2,p3] is an array of arrays.

What I am expecting?

An array of two float elements with 4 decimals of precission.

What I am getting?

An array of two float elements with no decimals precission.

What I want to know?

  1. Why the .round(4) method does not work in the context of my code?
  2. How can I use .round(4) within the context of my code in order to make it work properly?

CodePudding user response:

Your problem is not because the round(4) not working correctly. It's because part of code:

x0t = x0.div(3) # Always return Integer
x0tf = x0t.round(4)

I suggest using / instead of div:

 x0t = x0 / 3 # return Float
 x0tf = x0t.round(4)
  • Related