Convert & store String into currency values - ruby-on-rails

I have a String and i need to convert it into Currency format in RUBY and
verify whether it matches to the expected.
String = "$6,178.50 USD / 22,693.01 AED"
I want to split it into 2 different variables like
usa_price = $6,178.50
aed_price = 22,693.01
expected_output= $6,178.50 * 3.67 = 22,693.01 (should match value in AED)
I tried doing gsub/scan and im confused now, what's the best way to
achieve this in Ruby!!!

I would split on the / and then use the money gem to parse the amounts out, like this:
require 'money'
amounts = "$6,178.50 USD / 22,693.01 AED".split("/")
amounts.map! { |amount| Money.parse(amount) }
Then, because they're now Money objects, you can do money things with them:
>> amounts.first.format
=> "$6,178.50"

If you're sure that first number is USD and second number is AED and the order won't change then:
str = "$6,178.50 USD / 22,693.01 AED"
usa_price, aed_price = str.scan(/\d{1,2}?,?\d{1,3}\.\d{2}/)
#=> usa_price = 6,178.50, aed_price = 22,693.01

Related

cl_http_utility not normalizing my url. Why?

Via an enterpreise service consumer I connect to a webservice, which returns me some data, and also url's.
However, I tried all methods of the mentioned class above and NO METHOD seems to convert the unicode-characters inside my url into the proper readable characters.... ( in this case '=' and ';' ) ...
The only method, which runs properly is "is_valid_url", which returns false, when I pass url's like this:
http://not_publish-workflow-dev.hq.not_publish.com/lc/content/forms/af/not_publish/request-datson-internal/v01/request-datson-internal.html?taskId\u003d105862\u0026wcmmode\u003ddisabled
What am I missing?
It seems that this format is for json values. Usually = and & don't need to be written with the \u prefix. To decode all \u characters, you may use this code:
DATA(json_value) = `http://not_publish-workflow-dev.hq.not_publish.com/lc`
&& `/content/forms/af/not_publish/request-datson-internal/v01`
&& `/request-datson-internal.html?taskId\u003d105862\u0026wcmmode\u003ddisabled`.
FIND ALL OCCURRENCES OF REGEX '\\u....' IN json_value RESULTS DATA(matches).
SORT matches BY offset DESCENDING.
LOOP AT matches ASSIGNING FIELD-SYMBOL(<match>).
DATA hex2 TYPE x LENGTH 2.
hex2 = to_upper( substring( val = json_value+<match>-offset(<match>-length) off = 2 ) ).
DATA(uchar) = cl_abap_conv_in_ce=>uccp( hex2 ).
REPLACE SECTION OFFSET <match>-offset LENGTH <match>-length OF json_value WITH uchar.
ENDLOOP.
ASSERT json_value = `http://not_publish-workflow-dev.hq.not_publish.com/lc`
&& `/content/forms/af/not_publish/request-datson-internal/v01`
&& `/request-datson-internal.html?taskId=105862&wcmmode=disabled`.
I hate to answer my own questions, but anyway, I found an own solution, via manually replacing those unicodes. It is similar to Sandra's idea, but able to convert ANY unicode.
I share it here, just in case, any person might also need it.
DATA: lt_res_tab TYPE match_result_tab.
DATA(valid_url) = url.
FIND ALL OCCURRENCES OF REGEX '\\u.{4}' IN valid_url RESULTS lt_res_tab.
WHILE lines( lt_res_tab ) > 0.
DATA(match) = substring( val = valid_url off = lt_res_tab[ 1 ]-offset len = lt_res_tab[ 1 ]-length ).
DATA(hex_unicode) = to_upper( match+2 ).
DATA(char) = cl_abap_conv_in_ce=>uccp( uccp = hex_unicode ).
valid_url = replace( val = valid_url off = lt_res_tab[ 1 ]-offset len = lt_res_tab[ 1 ]-length with = char ).
FIND ALL OCCURRENCES OF REGEX '\\u.{4}' IN valid_url RESULTS lt_res_tab.
ENDWHILE.
WRITE / url.
WRITE / valid_url.

How to get float number in Lua from IUP text entry

I am trying following simple code to get a decimal value from user:
require( "iuplua" )
t1 = iup.text{expand = "YES", padding = "10x10", alignment="ARIGHT", size="40x"}
btn = iup.button {title = "Print:", padding = "10x10", alignment="ACENTER", size="40x"}
qbtn = iup.button{title="Quit", expand = "YES", padding = "10x10", alignment="ACENTER", size="40x"}
function btn:action()
strval1 = string.match (t1.value, "%d+")
print (strval1)
num = tonumber(strval1)
print (num)
end
function qbtn:action()
os.exit()
end
dlg = iup.dialog {
iup.vbox{
iup.hbox{
iup.label{title="Decimal:", padding = "10x10", alignment="ALEFT", size="40x"},
t1 },
iup.hbox{
btn,
qbtn }}}
dlg:show()
iup.MainLoop()
However, it prints out only an integer number (part before decimal- even 25.9999 prints as 25).
How can I get float or decimal value entered by user? Thanks for your help.
The problem with the code is that the pattern "%d+" in btn:action only gets the first run of digits.
You can change the pattern to handle decimal points, but it is hard to write a pattern that works in all cases, including optional sign and decimal point and scientific format.
It is best to let tonumber do its work: it will return nil if the string cannot be converted to a number.
Another option is to use the MASK attribute of the IupText to let the user only be able to enter numbers.

How to make a value_of_things function f#

Hey guys let's say I have a function that gets that day's rate of how much something costs, by the pound, and multiplies it by how many pounds a customer wants. i.e
let convert_func (crab_rate, lobster_rate);
//and then on a certain day it is
let (crab_rate, lobster_rate) = convert_fun(3.4, 6.8); // $3.8 a pound for crab, $6.8 a pound for lobster.
// 10 being how many pounds i want.
crab_rate10 ;
Then my out put would be whatever 38 since ($3.8 * 10lbs) = $38
I tried doing if statements so that when the user just wants to find out the total cost of one thing and not both. But I keep getting errors. I can't figure out how to store the rate values in the parameters and then calling the function.
This is what i tried
let crab_rate (pound, rate) = (float pound) * rate;
let lobster_rate (pound, rate) = (float pound) * rate;
let convert_func (crab_rate, lobster_rate)= function (first,second ) ->
if crab_rate then (float pound) * rate;
elif lobster_rate (float pound) * rate;
let (crab_rate, lobster_rate) = convert_fun(3.4, 6.8); // $3.8 a pound for crab, $6.8 a pound for lobster.
// 10 being how many pounds i want.
crab_rate10 ;
I think you should start by making a general function for converting a cost/weight and a weight into a cost. In F#, you can even use units of measure to help you:
[<Measure>] type USD // Unit of measure: US Dollars
[<Measure>] type lb // Unit of measure: lbs
let priceForWeight rate (weight : float<lb>) : float<USD> =
rate * weight
The nice thing about functional languages with curried arguments is that we can easily use partial function application. That means when we have a function that has two arguments, we can choose to supply just one argument and get back a new function from that one remaining argument to the result.
We can therefore define a further pair of functions that use this priceForWeight function.
let crabPriceForWeight weight = priceForWeight 3.8<USD/lb> weight
let lobsterPriceForWeight weight = priceForWeight 6.8<USD/lb> weight
Notice that we've used our original function to define two new functions with fixed rates.
We can then evaluate it like this:
let crabPrice10 = crabPriceForWeight 10.0<lb> // result 38.0<USD>
Of course, you can also define a function that returns both prices together as a tuple for a supplied weight:
let crabAndLobsterPriceForWeight weight =
crabPriceForWeight weight, lobsterPriceForWeight weight

Stata: multiplying each variable of a set of time-series variables with the corresponding variable of another set

Being fairly new to Stata, I'm having a difficulty figuring out how to do the following:
I have time-series data on selling price (p) and quantity sold (q) for 10 products in a single datafile (i,e., 20 variables, p01-p10 and q01-q10). I am strugling with appropriate stata command that computes sales revenue (pq) time-series for each of these 10 products (i.e., pq01-pq10).
Many thanks for your help.
forval i = 1/10 {
local j : display %02.0f `i'
gen pq`j' = p`j' * q`j'
}
A standard loop over 1/10 won't get you the leading zero in 01/09. For that we need to use an appropriate format. See also
#article {pr0051,
author = "Cox, N. J.",
title = "Stata tip 85: Looping over nonintegers",
journal = "Stata Journal",
publisher = "Stata Press",
address = "College Station, TX",
volume = "10",
number = "1",
year = "2010",
pages = "160-163(4)",
url = "http://www.stata-journal.com/article.html?article=pr0051"
}
(added later) Another way to do it is
local j = string(`i', "%02.0f")
That makes it a bit more explicit that you are mapping from numbers 1,...,10 to strings "01",...,"10".

Get an array from a string of numbers separated with comma

How can I convert a string like s = "6.1101,17.592,3.3245\n" to numbers in Lua.
In python, I usually do
a = s.strip().split(',')
a = [float(i) for i in a]
What is the proper way to do this with Lua?
This is fairly trivial; just do a repeated match:
for match in s:gmatch("([%d%.%+%-]+),?") do
output[#output + 1] = tonumber(match)
end
This of course assumes that there are no spaces in the numbers.

Resources