I'm trying to solve a problem :
Your task is to write a simple function that takes a number of meters, and outputs it using metric prefixes.For this exercise we just want units bigger than a meter, from meters up to yottameters, excluding decameters and hectometers.All values passed in will be positive integers Examples
meters(51500)
# returns "51.5km"
meters(5000000)
# returns "5Mm"
My code:
def meters(x)
map_prefix={ 24=>'Y', 21=> 'Z', 18=> 'E', 15=> 'P', 12=> 'T', 9=>'G', 6=>'M', 3=>'k',0=>'' }
digits=(x.to_i.to_s.size-1)/3
division=x/(10.0**(3*digits))
"#{division}#{map_prefix[3*digits]}m".sub(/\.0([^\d])/,'\1')
end
It doesn't work for meters(56*10**24) #->expected 56Ym ,instead got 56.000000000004Ym, but it works for bigger numbers such as meters(88*10**24) #->88Ym. The code passes 49 out of 50 tests, can someone help me find the error?
I think your issue is that you are multiplying by
10.0, yet you only want to deal with integers.Something like the following is what you want. (I'm also doing a couple style changes).
This at least gives the correct solution to the one that is wrong. I'm not going to guarantee it is the correct solution to everything.
I made the hash into its own function here because it seems like it would be static. As well was the other things I mentioned in my comment.