Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 20 total

single-line-reformat - Reformats a block/object to a single line if it's short enough

    single-line-reformat: func [
        "Reformats a block/object to a single line if it's short enough."
        val [any-string!] /local s map
    ] [
        either 80 >= length? s: trim/lines copy val [
            map: ["{ " "{"  "[ " "["  " }" "}"  " ]" "]"]
            foreach [from to] map [replace s from to]
        ] [val]
    ]

Number to Currency with Cents

A slight alteration to the default Rails currency formatting helper to show numbers in cents if the number is less than $1.00. For example $0.99 would instead become 99¢.

def number_to_currency_with_cents(number, options = {})
    options = options.stringify_keys
    precision = options.delete('precision') { 2 }
    unit = options.delete('unit') { '$' }
    fractional_unit = options.delete('fractional_unit') { '¢' }
    separator = options.delete('separator') { '.' }
    delimiter = options.delete('delimiter') { ',' }
    separator = '' unless precision > 0
    begin
        fraction = number.abs % 1.0
        body = number.floor
        if body != 0 || body == 0 && fraction == 0 then
            parts = number_with_precision(number, precision).split('.')
            unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s
        else
            (fraction * 100).to_i.to_s + fractional_unit
        end
    rescue
        number
    end
end


I'm really tempted to go through and replace that whole thing with my own code, but it works, so I'm happy.

Gmail Date Format Helper

I needed a short and intuitive way of showing dates, so rather than just making something up I decided to steal Google's short date format from Gmail. I'm sure they did usability studies and whatnot.

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
  :gmail => lambda { |date|
    Time.now.beginning_of_day <= date ?
    "#{date.strftime('%I').to_i}:#{date.strftime('%M')} #{date.strftime('%p').downcase}" :
    Time.now.beginning_of_year <= date ?
    "#{date.strftime('%b')} #{date.day}" :
    "#{date.month}/#{date.day}/#{date.strftime('%y')}"
  }
)

ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
  :gmail => lambda { |date|
    Time.now.beginning_of_day <= date ?
    "#{date.strftime('%I').to_i}:#{date.strftime('%M')} #{date.strftime('%p').downcase}" :
    Time.now.beginning_of_year <= date ?
    "#{date.strftime('%b')} #{date.day}" :
    "#{date.month}/#{date.day}/#{date.strftime('%y')}"
  }
)


Put this code in your "environmen.rb" file in your "RAILS_ROOT/config" directory or make a new Ruby script file containing it in your "RAILS_ROOT/config/initializers" directory.

RoR Date Formats

From http://hittingthebuffers.com/2006/08/11/date-formats/:
August 11, 2006
Date formats

Here's a handy date related tip I just read when I was looking around for ways to make an RSS feed valid.

If you go to a command line and run script/console, then type ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS it displays a hash containing default date formatting which can be used with to_s() like this:
      xml.pubDate(article.created_at.to_s(:rfc822))


It's also possible to add additional formats to the end of application.rb:
      ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
        :default => "%m/%d/%Y",
        :date_time12 => "%m/%d/%Y %I:%M%p",
        :date_time24 => "%m/%d/%Y %H:%M"
      )


From Comments (as of 2006.08.14):
2.
My personal faves:
      :iso_8601_date_only =>%Y-%m-%d’,
      :iso_8601_time_only =>%H:%M:%S%z’

Comment by Todd Sayre — August 12, 2006 @ 3:19 pm

Csharp format integer as hex string

// Using the built in ability to print a byte as a hex value
// this set of methods gives the ability to print shorts
// and longs as hex using the spacing that is customary.

using System;

namespace testApp
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Class1
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			Class1 t = new Class1();
			long i = 12; // 
			Console.WriteLine(t.int32ToHexString(i));
		}

		private string int32ToHexString(long i)
		{
			byte[] int32Bytes;
			int32Bytes = BitConverter.GetBytes(i);
			return String.Format("{0}{1}{2}{3}",
				padString(int32Bytes[0].ToString("X")),
				padString(int32Bytes[1].ToString("X")),
				padString(int32Bytes[2].ToString("X")),
				padString(int32Bytes[3].ToString("X")));
		}

		private string int16ToHexString(short i)
		{
			byte[] int32Bytes;
			int32Bytes = BitConverter.GetBytes(i);
			return String.Format("{0}{1}",
				padString(int32Bytes[0].ToString("X")),
				padString(int32Bytes[1].ToString("X")));
		}

		private string byteToHexString(byte b)
		{
			return padString(String.Format("{0}", b.ToString("X")));
		}

		private string padString(string s)
		{
			while (s.Length < 2) s = "0" + s;
			while (s.Length < 3) s = " " + s;
			return s;
		}
	}
}



produces this output:
0C 00 00 00

Csharp formatting an integer as a binary string representation

// description of your code here

using System;

namespace testApp
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Class1
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			Class1 t = new Class1();
			long i = 12; // 
			Console.WriteLine(t.ConvertByteToBinaryString(i));
		}
		/// <summary>
		/// Format integer as a binary string with spaces between every 4 bits
		/// </summary>
		/// <param name="input">integer to format</param>
		/// <returns>string of the form "0000 0000 0000 0000 0000 0110 0001 1000"</returns>
		private string ConvertByteToBinaryString(long input)
		{
			string result = null;
			string bitstring = null;
			for(int i=31;i>=0;i--)
			{
				if (((input >> i) & 1) == 1) result = "1";
				else result = "0";
				bitstring += result;
				if ((i>0) && ((i)%4)==0)
				{
					bitstring += " ";
				}
			}
			return bitstring;
		}
	}
}

produces this output:
0000 0000 0000 0000 0000 0000 0000 1100

Python % formating

# format % 2
%d     : '2'
%5d    : '    2'
%-5d   : '2    '
%05d   : '00002'
%.2e   : '2.00e+000'
%.2f   : '2.00'

%s     : string, applying str()
%-20s  : left-adjust

Formatting time

>>> from e32db import format_time
>>> from time import *
>>> t = time()
>>>
>>> format_time(t)   # for Symbian SQL
u'06/03/2006 23:26:35'
>>> strftime('%d/%m/%Y %H:%M:%S')  # like above
'06/03/2006 23:26:39'
>>> ctime()
'Mon Mar 06 23:26:49 2006'
>>> strftime("%a, %d %b %Y %H:%M:%S +0000")  # email RFC
'Mon, 06 Mar 2006 23:26:59 +0000'

Here's the (shortened) table for strftime.
%a  weekday name.  
%A  weekday name (full).  
%b  month name.  
%B  month name (full).  
%c  date and time (locale)
%d  day of month [01,31].  
%H  hour [00,23].  
%I  hour [01,12].  
%j  day of year [001,366].  
%m  month [01,12].  
%M  minute [00,59].  
%p  AM or PM
%S  Second [00,61]
%U  week of year (Sunday)[00,53].
 w  weekday [0(Sunday),6].
 W  week of year (Monday)[00,53].
 x  date (locale).
%X  time (locale).
%y  year [00,99].
%Y  year [2000].
%Z  timezone name.  

add thousands separators to numbers

I've finally figured out how to add thousands separators.

If there's a built in for this (like a `sprintf` parameters) I don't want to hear it. I just don't, ok?

def ts( st )
  st = st.reverse
  r = ""
  max = if st[-1].chr == '-'
    st.size - 1
  else
    st.size
  end
  if st.to_i == st.to_f
    1.upto(st.size) {|i| r << st[i-1].chr ; r << ',' if i%3 == 0 and i < max}
  else
    start = nil
    1.upto(st.size) {|i|
      r << st[i-1].chr
      start = 0 if r[-1].chr == '.' and not start
      if start
        r << ',' if start % 3 == 0 and start != 0  and i < max
        start += 1
      end
    }
  end
  r.reverse
end


That's it.

puts ts('100')
puts ts('1')
puts ts('1000')
puts ts('1000000.01')
puts ts('100046546510000.022435451')
puts ts('-100')
puts ts('-1')
puts ts('-1000')
puts ts('-1000000.01')
puts ts('-100046546510000.022435451')


outputs:

100
1
1,000
1,000,000.01
100,046,546,510,000.022435451
-100
-1
-1,000
-1,000,000.01
-100,046,546,510,000.022435451


It's ugly, yeah, but it works.

Format Currency //Javascript Function


Formats strings/numbers into "money format" without loops :)

Defaults:
float ploint cutoff = 2 decimal places
decimal separator = ','
thousands separator = '.'

[UPDATED CODE AND HELP CAN BE FOUND HERE]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/number/fmt-money [v1.1]

Number.prototype.formatMoney = function(c, d, t){
	var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};



Usage

(123456789.12345).formatMoney(2, '.', ',');
« Newer Snippets
Older Snippets »
Showing 11-20 of 20 total