rails format positive and negative numbers - ruby

I'm trying to format a column of numbers in rails - using number_to_currency. I want to display negative numbers with ()s - which is easy to do using the negative_format option. However, when I do this, the decimal points in a column of numbers doesn't line up. I want to add a trailing space to the format for positive numbers - %u%n, only I don't know how to do that - can anyone give me the right way to format in a trailing space?

There are a couple of ways you can pad the positive numbers with a little bit of space, either:
Use a fixed width font and a nonbreaking space
Apply a class to the enclosing element of your positive numbers (or wrap in a span) and then use internal padding to add space to the right.
The first approach mixes presentation with content, but has the advantage of working with any font size (or user resized fonts). With the second solution your HTML is cleaner and in well-behaved browsers things will work well, but your mileage will vary with less modern ones.
Here's a quick implementation of the first option:
def pad_positives(number_string)
unless number_string[0,1] == '('
number_string += '%nbsp;'
end
number_string
end
You could drop this in your appropriate helper file and then do something like this in your view:
<%= pad_positives(number_to_currency(number, ...)) %>
Note this function expects a string, so it will choke if you pass it a number. Hope this helps!

Let's say you have the variable amount in your loop:
<td class="amount">
<%= (amount >= 0) ? "#{number_to_currency(amount)} " : "(#{number_to_currency(amount)})" %>
</td>
And in your CSS:
.amount {
font-family:monospace;
}

Related

Ruby pack and Latin (high-ASCII) characters

An action outputs a fixed-length string via Ruby's pack function
clean = [edc_unico, sequenza_sede, cliente_id.to_s, nome, indirizzo, cap, comune, provincia, persona, note, telefono, email]
string = clean.pack('A15A5A6A40A35A5A30A2A40A40A18A25')
However, the data is in UTF-8 as to allow latin/high-ascii characters. The result of the pack action is logical. high-ascii characters take the space of 2 regular ascii characters. The resulting string is shortened by 1 space character, defeating the original purpose.
What would be a concise ruby command to interpret high-ascii characters and thus add an extra space at the end of each variable for each high-ascii character, so that the length can be brought to its proper target? (note: I am assuming there is no directive that addresses this specifically, and the whole lot of pack directives is mind-muddling)
update an example where the second line shifts positions based on accented characters
CNFrigo 539 Via Privata Da Via Iseo 6C 20098San Giuliano Milanese MI02 98282410 02 98287686 12886480156 12886480156 Bo3 Euro Giuseppe Frigo Transport 349 2803433 M.Gianoli#Delanchy.Fr S.Galliard#Delanchy.Fr
CNIn's M 497 Via Istituto S.Maria della Pietà, 30173Venezia Ve041 8690111 340 6311408 0041 5136113 00115180283 02896940273 B60Fm Euro Per Documentazioni Tecniche Inviare Materiale A : Silvia_Scarpa#Insmercato.It Amministrazione : Michela_Bianco#Insmercato.It Silvia Scarpa Per Liberatorie 041/5136171 Sig.Ra Bianco Per Pagamento Fatture 041/5136111 (Solo Il Giovedi Pomeriggio Dalle 14 All Beniservizi.Insmercato#Pec.Gruppopam.It
It looks like you are trying to use pack to format strings to fixed width columns for display. That’s not what it’s for, it is generally used for packing data into fixed byte structures for things like network protocols.
You probably want to use a format string instead, which is better suited for manipulating data for display.
Have a look at String#% (i.e. the % method on string). Like pack it uses another little language which is defined in Kernel#sprintf.
Taking a simplified example, with the two arrays:
plain = ["Iseo", "Next field"]
accent = ["Pietà", "Next field"]
then using pack like this:
puts plain.pack("A10A10")
puts accent.pack("A10A10")
will produce a result that looks like this, where “Next field” isn’t aligned since pack is dealing with the width in bytes, not the displayed width:
Iseo Next field
Pietà Next field
Using a format string, like this:
puts "%-10s%-10s" % plain
puts "%-10s%-10s" % accent
produces the desired result, since it is dealing with the displayable width:
Iseo Next field
Pietà Next field

Automatically increment filename VideoWriter MATLAB

I have MATLAB set to record three webcams at the same time. I want to capture and save each feed to a file and automatically increment it the file name, it will be replaced by experiment_0001.avi, followed by experiment_0002.avi, etc.
My code looks like this at the moment
set(vid1,'LoggingMode','disk');
set(vid2,'LoggingMode','disk');
avi1 = VideoWriter('X:\ABC\Data Collection\Presentations\Correct\ExperimentA_002.AVI');
avi2 = VideoWriter('X:\ABC\Data Collection\Presentations\Correct\ExperimentB_002.AVI');
set(vid1,'DiskLogger',avi1);
set(vid2,'DiskLogger',avi2);
and I am incrementing the 002 each time.
Any thoughts on how to implement this efficiently?
Thanks.
dont forget matlab has some roots to C programming language. That means things like sprintf will work
so since you are printing out an integer value zero padded to 3 spaces you would need something like this sprintf('%03d',n) then % means there is a value to print that isn't text. 0 means zero pad on the left, 3 means pad to 3 digits, d means the number itself is an integer
just use sprintf in place of a string. the s means String print formatted. so it will output a string. here is an idea of what you might do
set(vid1,'LoggingMode','disk');
set(vid2,'LoggingMode','disk');
for (n=1:2:max_num_captures)
avi1 = VideoWriter(sprintf('X:\ABC\Data Collection\Presentations\Correct\ExperimentA_%03d.AVI',n));
avi2 = VideoWriter(sprintf('X:\ABC\Data Collection\Presentations\Correct\ExperimentB_002.AVI',n));
set(vid1,'DiskLogger',avi1);
set(vid2,'DiskLogger',avi2);
end

Force Ruby to not output a float in standard form / scientific notation / exponential notation

I have the same problem as is found here for python, but for ruby.
I need to output a small number like this: 0.00001, not 1e-5.
For more information about my particular problem, I am outputting to a file using f.write("My number: " + small_number.to_s + "\n")
For my problem, accuracy isn't that big of an issue, so just doing an if statement to check if small_number < 1e-5 and then printing 0 is okay, it just doesn't seem as elegant as it should be.
So what is the more general way to do this?
f.printf "My number: %.5f\n", small_number
You can replace .5 (5 digits to the right of the decimal) with any particular formatting size you like, e.g., %8.3f would be total of 8 digits with three to the right of the decimal, much like C/C++ printf formatting strings.
If you always want 5 decimal places, you could use:
"%.5f" % small_number
I would do something like this so you can strip off trailing zero's:
puts ("%.15f" % small_number).sub(/0*$/,"")
Don't go too far past 15, or you will suffer from the imprecision of floating point numbers.
puts ("%.25f" % 0.01).sub(/0*$/,"")
0.0100000000000000002081668
This works also on integers, trim excess zeros, and always returns numbers as a valid floating point number. For clarity, this uses the sprintf instead of the more cryptic % operator.
def format_float(number)
sprintf('%.15f', number).sub(/0+$/, '').sub(/\.$/, '.0')
end
Examples:
format_float(1) => "1.0"
format_float(0.00000001) => "0.00000001"

Ruby: Fuzzing through all unicode characters ‎(UTF8/Encoding/String Manipulation)

I can't iterate over the entire range of unicode characters.
I searched everywhere...
I am building a fuzzer and want to embed into a url, all unicode characters (one at a time).
For example:
http://www.example.com?a=\uff1c
I know that there are some built tools but I need more flexibility.
If i could do someting like the following: "\u" + "ff1c" it would be great.
This is the closest I got:
char = "\u0000"
...
#within iteration
char.succ!
...
but after the character "\u0039", which is the number 9, I will get "10" instead of ":"
You could use pack to convert numbers to UTF8 characters but I'm not sure if this solves your problem.
You can either create an array with numeric values of all the characters and use pack to get an UTF8 string or you can just loop from 0 to whatever you need and use pack within the loop.
I've written a small example to explain myself. The code below prints out the hex value of each character followed by the character itself.
0.upto(100) do |i|
puts "%04x" % i + ": " + [i].pack("U*")
end
Here's some simpler code, albeit slightly obfuscated, that takes advantage of the fact that Ruby will convert an integer on the right hand side of the << operator to a codepoint. This only works with Ruby 1.8 up for integer values <= 255. It will work for values greater than 255 in 1.9.
0.upto(100) do |i|
puts "" << i
end

Suppressing a trailing "." in numerical output from Mathematica

Is there some straightforward way to ensure that, when converted to strings, approximate numbers (i.e., numbers with the Real head) won't have a trailing "."? I would like it if they were to only have the decimal point in cases where there's actually a displayed fractional part.
The solutions I've found are not robust, and depend on using Precision and Accuracy together NumberForm in an awkward way, or using RealDigits in an even more awkward way.
Thanks in advance.
I've used this in the past when displaying numbers in figures:
Integerise[x_] := If[Round[x] == x, ToString[Round#x] <> ".0", ToString#x]
Just remove <> ".0" if you don't want integers to be displayed with a zero decimal.
Update: As mentioned by dreeves in the comment, ToString will still truncate a number within 0.0001 or so of an integer and display the dot.
A better way to remove the trailing dot is to use the Inputform format for ToString:
NormalNumber[x_] := ToString[x, InputForm]
with a test:
NormalNumber /# {5, 5.5, 123.001, 123.0001}
This could be incorporated into Integerise above to fix the problem noted.
I recommend this:
shownum[x_] := StringReplace[ToString#NumberForm[x, ExponentFunction->(Null&)],
RegularExpression["\\.$"]->""]
It just does a regex search&replace on the trailing ".". If you want "123." to display as "123.0" instead of "123" then just replace that final empty string with ".0".
UPDATE: My original version displayed wrong for numbers that Mathematica by default displays in scientific notation.
I fixed that with NumberForm.
Here's the version I actually use in real life. It allows for optional rounding:
(* Show Number. Convert to string w/ no trailing dot. Round to the nearest r. *)
Unprotect[Round]; Round[x_,0] := x; Protect[Round];
re = RegularExpression;
shn[x_, r_:0] := StringReplace[
ToString#NumberForm[Round[N#x,r], ExponentFunction->(Null&)], re#"\\.$"->""]
I'd probably just post-process the string. It's faster (and way easier) to just check if the last character is "." than to do redundant arithmetic and take into account all the precision settings.
Edit: maybe you know this, but you can do something like this:
userToString[expr_, form___] := ToString[expr,form];
userToString[expr_Real, form___] := removeTrailingDot[ToString[expr,form]];
The functions NumberForm, ScientificForm, EngineeringForm, etc. ... offers the option NumberFormat to format and arrange the mantissa, base and exponent of a number. With
numberTrim[expr_] := NumberForm[expr,
NumberFormat -> (Row[{StringTrim[#1, "."],
If[#3 == "", "", "\[ThinSpace]\[Times]\[ThinSpace]" <> #2^#3]}] &)];
the default Mathematica output is reproduced, but the trailing dot is removed.

Resources