how to print floats with 6 digits only - Ruby - ruby

Okay..
I have these float numbers in a ruby array :-)
12.321912389
122.438783
345.23242444
89.37827383
I want to convert these numbers to 6 digits numbers without losing float property.
something like :-)
12.3219
122.438
345.232
89.3782
Which function can help me? sorry if this question is very naive to you :-)

You can play with sprintf "g" format, what you need is 6 significant digits:
(0..6).map{|i| '%.6g' % (10.0**i / 3)}
=> ["0.333333", "3.33333", "33.3333", "333.333", "3333.33", "33333.3", "333333"]

This is very stupid (and slow), but it works (assuming numbers contain decimal point):
numbers = [12.321912389, 122.438783, 345.23242444, 89.37827383]
numbers.map! { |num| num.to_s[0..6].to_f }
p numbers #=> [12.3219, 122.438, 345.232, 89.3782]

Related

How do I rounding of zeros in Ruby

When I round of 12121.232323 to 2 digit decimal point like below
p 12121.232323.round(2)
it is printing
12121.23
But when I try to round()
211211.00000.round(2)
it's printing
211211.0
But I want
211211.00
How do I do that?
'%.2f' % 12121.232323
or
include ActionView::Helpers::NumberHelper
number_with_precision(value, :precision => 2)
What you seek is not exactly rounding but formatting.
You can select your float formatting like this:
p "%.2f" % 12121.0000
where the %.2f part means "show 2 decimal points"

Float - two digits after comma - how to?

I tried to execute a calculation in Ruby. The result I get is 1589.5833333333333. I would like to limitat the numbers of digits after the comma.
The result should always be limited to 2 digits as followed:
1589.58
Question #1 = how can I set the limitation?
Question #2 = how can I round up 1589.60 or down 1589.55
Many thanks for help. Language is ruby
Other option but keeping the object as Float:
n = 1589.5833333333333
m = n.truncate(2) #=> 1589.58
h = n.round(1) #=> 1589.6 # for the last zero you need to format the string
And a tricky:
k = (n*100).to_i.digits.tap{ |ary| ary.first > 5 ? ary[0] = 5 : ary[0] = 0 }.reverse.join('').to_i/100.0
#=> 1589.55
For question 1:
num = 1589.5833333333333
printf('%.2f', num)
=> 1589.58
For question 2 to round up to first digit:
num = 1589.5833333333333
printf('%.2f', num.round(1))
=> 1589.60
1589.55 is a bit of an arbitrary number, rounding down would usually be calculated as 1589.58. I don't know of any Ruby function that does that off-hand.

How to get the randrange equivalent of python in Ruby

I want to get a random value between 0 and 20 but skips by 3, like the python equivalent of:
random.randrange(0,20, 3)
Here's a one-liner:
(0...20).to_a.keep_if {|z| z % 3 == 0}.sample
And bjhaid's example will work if you make the top number the first number that is equal or greater that is divisible by 3, i.e.:
rand(21 / 3) * 3
But you would have to manually set that upper number depending on what your slice size and upper number are.
My one-liner is kind of ugly to me, if I were using it in just one place in an entire program I might use it. but if I was going to re-use it I'd make a method: edit I just noticed #cremno answer in the comments. I like their step version better than mine. I'd use that in a method:
def randrange(lower, upper, grouping)
(lower...upper).step(grouping).to_a.sample
end
my old method...
def randrange(lower, upper, grouping)
arr = (lower...upper).to_a.keep_if {|i| i % grouping == 0}
arr.sample
end

Iteration order

I'm working on Project Euler problem #4:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
My code as follows is wrong:
def ispalindrome?(number)
number.to_s == number.to_s.reverse
end
palindromes = []
(100..999).each { |x|
(100..999).each { |y|
palindromes.push (x * y) if ispalindrome?(x * y)
}
}
palindromes.last # => 580085
What's going on here?
This has nothing to do with ruby. Simple math :)
Replace palindromes.last with palindromes.max
As someone else said, replacing palindromes.last with palindromes.max will work.
The reason is that, as products of three-digit numbers, 580085 = 995 * 583 and 906609 = 993 * 913.
Think carefully about the order in which you consider pairs of x and y. If you consider (993, 913) and then later (995, 583) (as happens in the first and third examples), then the last palindrome found will be 580085.
You just forgot to sort your array before taking the value, I used your code from the first try just added
palindromes.sort
and it gave me 906609
The problem is that you are not returning the biggest number but the last number that was added , and it depends on the order you loop through the numbers.
you need to change your last command to:
puts palindromes.max

Split float into integer and decimals in Ruby

If I have a float like 3.75, how can I split it into the integer 3 and the float 0.75?
Do I have to convert the float into a string, and then split the string by ".", and then convert the parts into integers and floats again, or is there a more elegant or "right" way to do this?
You can use Numeric#divmod with argument 1 for this:
Returns an array containing the quotient and modulus obtained by dividing num by numeric.
a.divmod 1
=> [3, 0.75]
If you want to get precise value, this method is available for BigDecimal as well:
3.456.divmod 1
=> [3, 0.45599999999999996]
require 'bigdecimal'
div_mod = BigDecimal("3.456").divmod 1
[div_mod[0].to_i, div_mod[1].to_f]
=> [3, 0.456]
As mentioned you can use 3.75.to_i to get the integer.
An alternate way to get the remainder is using the % operator eg.
3.75 % 1
puts "frac = #{(3.456).to_s.split(".").last.prepend("0.").to_f}"
puts "Integer part = #{(3.456).truncate}"

Resources