EzDevInfo.com

money

PHP implementation of Fowler's Money pattern. NOTE: all work is happening in the "nextrelease" branch, which will break BC. Representing Money in PHP, Fowler-style independent software consultant

PHP: unformat money

Is there a way to get the float value of a string like this: 75,25 €, other than parsefloat(str_replace(',', '.', $var))?

I want this to be dependent on the current site language, and sometimes the comma could be replaced by dot.


Source: (StackOverflow)

Print Currency Number Format in PHP

I have some price values to display in my page.

I am writing a function which takes the float price and returns the formatted currency val with currency code too..

For example, fnPrice(1001.01) should print $ 1,000.01


Source: (StackOverflow)

Advertisements

Regex for Money

I have asp:TextBox to keep a value of money, i.e. '1000', '1000,0' and '1000,00' (comma is the delimiter because of Russian standard).

What ValidationExpression have I to use into appropriate asp:RegularExpressionValidator?

I tried \d+\,\d{0,2} but it doesn't allows a number without decimal digits, e.g. just '1000'.


Source: (StackOverflow)

Ruby on Rails: best method of handling currency / money

I'm new to Ruby on Rails and I'm working on a very basic shopping cart system. I have a table items that has a column price of type integer. I'm having trouble displaying the price value in my views for prices that include both Euros and cents. Am I missing something obvious as far as handling currency in the Rails framework is concerned?


Source: (StackOverflow)

What is the best data type to use for money in c#?

What is the best data type to use for money in c#?


Source: (StackOverflow)

Representing Monetary Values in Java [closed]

I understand that BigDecimal is recommended best practice for representing monetary values in Java. What do you use? Is there a better library that you prefer to use instead?


Source: (StackOverflow)

storing money amounts in mysql

I want to store 3.50 into a mysql table. I have a float that I store it in, but it stores as 3.5, not 3.50. How can I get it to have the trailing zero?


Source: (StackOverflow)

How do I format a double to currency rounded to the nearst dollar?

Right now I have

double numba = 5212.6312
String.Format("{0:C}", Convert.ToInt32(numba) )

This will give me

$5,213.00

but I don't want the ".00".

I know I can just drop the last three characters of the string every time to achieve the effect, but seems like there should be an easier way.


Source: (StackOverflow)

Java: Currency to Locale Mapping Possible?

I have a value stored in a DB correlating to a monetary amount, say 10.0. I also have access to the Currency/CurrencyCode. How can I use NumberFormat/DecimalFormat/(other?) to format when I don't know the Locale? According to the docs it will pick a default locale which won't work with a foreign Currency.


Source: (StackOverflow)

Should I do money calculations in Javascript or as an AJAX call?

I'm building a webapp using JQuery, Stripes, Spring and JPA (Hibernate).

I have a page that allows users to enter a number of order line items and each time onblur occurs in the price field, I have a JQuery event bound to the field which sums all the price fields (this is a subtotal), calculates 10% tax and adds the tax to the subtotal. I update the page to display the subtotal, tax and grand total.

My question is, should I be doing this calculation in Javascript? If so, how can I be sure the rounding etc is working correctly? I'm a bit worried about problems with precision.

Would it be better for me to make an Ajax call to do the calculation in Java?

Any advice would be great!


Source: (StackOverflow)

How should I use EditorFor() in MVC for a currency/money type?

In my view I have the following call.

<%= Html.EditorFor(x => x.Cost) %>

I have a ViewModel with the following code to define Cost.

public decimal Cost { get; set; }

However this displays a decimal value with four digits after the decimal (e.g. 0.0000). I am aware of Decimal.toString("G") (MSDN) which appears to solve this issue, but I'm uncertain of where to apply it.

One solution seems to be create a partial view "Currency.aspx".

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Decimal>" %>
<%= Html.TextBox(Model.ToString("g"), new { @class = "currency" }) %>

And a [UIHint("Currency")] in my ViewModel.

This seems inelegant. I assume that this problem has been solved tidily somewhere in the MVC framework or C# but I am unaware of cleaner solutions.

What is the appropriate way to handle editing currency values in MVC?


Source: (StackOverflow)

How to parse a currency Amount (US or EU) to float value in Java

In Europe decimals are separated with ',' and we use optional '.' to separate thousands. I allow currency values with:

  • US-style 123,456.78 notation
  • European-style 123.456,78 notation

I use the next regular expression (from RegexBuddy library) to validate the input. I allow optional two-digits fractions and optional thousands separators.

^[+-]?[0-9]{1,3}(?:[0-9]*(?:[.,][0-9]{0,2})?|(?:,[0-9]{3})*(?:\.[0-9]{0,2})?|(?:\.[0-9]{3})*(?:,[0-9]{0,2})?)$

I would like to parse a currency string to a float. For example

123,456.78 should be stored as 123456.78
123.456,78 should be stored as 123456.78
123.45 should be stored as 123.45
1.234 should be stored as 1234 12.34 should be stored as 12.34

and so on...

Is there an easy way to do this in Java?

public float currencyToFloat(String currency) {
    // transform and return as float
}

Use BigDecimal instead of Float


Thanks to everyone for the great answers. I have changed my code to use BigDecimal instead of float. I will keep previous part of this question with float to prevent people from doing the same mistakes I was gonna do.

Solution


The next code shows a function which transforms from US and EU currency to a string accepted by BigDecimal(String) constructor. That it is to say a string with no thousand separator and a point for fractions.

   import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class TestUSAndEUCurrency {

    public static void main(String[] args) throws Exception {		
    	test("123,456.78","123456.78");
    	test("123.456,78","123456.78");
    	test("123.45","123.45");
    	test("1.234","1234");
    	test("12","12");
    	test("12.1","12.1");
    	test("1.13","1.13");
    	test("1.1","1.1");
    	test("1,2","1.2");
    	test("1","1");				
    }

    public static void test(String value, String expected_output) throws Exception {
    	String output = currencyToBigDecimalFormat(value);
    	if(!output.equals(expected_output)) {
    		System.out.println("ERROR expected: " + expected_output + " output " + output);
    	}
    }

    public static String currencyToBigDecimalFormat(String currency) throws Exception {

    	if(!doesMatch(currency,"^[+-]?[0-9]{1,3}(?:[0-9]*(?:[.,][0-9]{0,2})?|(?:,[0-9]{3})*(?:\\.[0-9]{0,2})?|(?:\\.[0-9]{3})*(?:,[0-9]{0,2})?)$"))
    			throw new Exception("Currency in wrong format " + currency);

    	// Replace all dots with commas
    	currency = currency.replaceAll("\\.", ",");

    	// If fractions exist, the separator must be a .
    	if(currency.length()>=3) {
    		char[] chars = currency.toCharArray();
    		if(chars[chars.length-2] == ',') {
    			chars[chars.length-2] = '.';
    		} else if(chars[chars.length-3] == ',') {
    			chars[chars.length-3] = '.';
    		}
    		currency = new String(chars);
    	}

    	// Remove all commas		
    	return currency.replaceAll(",", "");				
    }

    public static boolean doesMatch(String s, String pattern) {
    	try {
    		Pattern patt = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
    		Matcher matcher = patt.matcher(s);
    		return matcher.matches();
    	} catch (RuntimeException e) {
    		return false;
    	}           
    }  

}

Source: (StackOverflow)

Proof that Fowler's money allocation algorithm is correct

Martin Fowler has a Money class that has a money allocation routine. This routine allocates money according to a given list of ratios without losing any value through rounding. It spreads any remainder value over the results.

For example, $100 allocated by the "ratios" (1, 1, 1) would yield ($34, $33, $33).

Here is the allocate function:

public long[] allocate(long amount, long[] ratios) {
    long total = 0;
    for (int i = 0; i < ratios.length; i++) total += ratios[i];

    long remainder = amount;
    long[] results = new long[ratios.length];
    for (int i = 0; i < results.length; i++) {
        results[i] = amount * ratios[i] / total;
        remainder -= results[i];
    }

    for (int i = 0; i < remainder; i++) {
        results[i]++;
    }

    return results;
}

(For the sake of this question, to make it simpler, I've taken the liberty of replacing the Money types with longs.)

The question is, how do I know it is correct? It all seems pretty self-evident except for the final for-loop. I think that to prove the function is correct, it would be sufficient to prove that the following relation is true in the final for-loop:

remainder < results.length

Can anyone prove that?


Source: (StackOverflow)

How to send a USSD code containing decimal floating point (.)?

I need to send a USSD code containing a double value, that represents the balance account amount to be transferred. This value is composed by an integer number, and optionally a decimal separator and 2 more digits. My code looks as follows:

    double doubleValue = 0.70;
    String phoneNumber = "51234567", pincode = "1234";
    String ast = Uri.encode("*");
    String baseUssd = ast + "234" + ast + "1" + ast + phoneNumber + ast + pincode + ast;
    StringBuilder builder = new StringBuilder();
    builder.append(baseUssd);
    builder.append(doubleValue); //i.e: 1.35, 0.80
    builder.append(Uri.encode("#"));
    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + builder.toString()));
    startActivity(intent);

My phone treats the doubleValue as 135, 080, etc. ignoring the dot separator character. I hope the final code includes "dot", allowing send the decimal value. Someone solved this problem?


Source: (StackOverflow)

Is SQL Server 'MONEY' data type a decimal floating point or binary floating point?

I couldn't find anything that rejects or confirms whether SQL Server 'MONEY' data type is a decimal floating point or binary floating point.

In the description it says that MONEY type range is from -2^63 to 2^63 - 1 so this kind of implies that it should be a binary floating point.

But on this page it lists MONEY as "exact" numeric. Which kind of suggests that MONEY might be a decimal floating point (otherwise how is it exact? or what is the definition of exact?)

Then if MONEY is a decimal floating point, then what is the difference between MONEY and DECIMAL(19,4) ?


Source: (StackOverflow)