how to convert string to float using locale language fr_FR in configuration
for example:
my_str = '546 587,44'
I created a function:
def get_float(value):
if not value: return None
lang=self.env['res.lang'].search([('code','=',env.context.get('lang'))])
return float(value.replace(lang.thousands_sep, '')
.replace(lang.decimal_point, '.'))
then just use it as
get_float(str)
Related
I'm using C++ Builder and my locale is European, so I have a comma as a decimal separator.
I need to convert a double to a decimal point value with a DOT as separator.
I can't find an answer anywhere.
DecimalSeparator is a global variable, simply set it to the desired character before formatting the double, eg:
#include <SysUtils.hpp>
System::String FormatWithDot(double value)
{
System::Char old = Sysutils::DecimalSeparator;
Sysutils::DecimalSeparator = _D('.');
System::String s = Sysutils::FloatToStr(value);
Sysutils::DecimalSeparator = old;
return s;
}
System::String s = FormatWithDot(123.45);
Or, if you need to do this in multiple threads, use the thread-safe version, TFormatSettings::DecimalSeparator:
#include <SysUtils.hpp>
System::String FormatWithDot(double value)
{
Sysutils::TFormatSettings fmt = Sysutils::TFormatSettings::Create();
fmt.DecimalSeparator = _D('.');
return Sysutils::FloatToStr(value, fmt);
}
System::String s = FormatWithDot(123.45);
Just note that DecimalSeparator only applies to Delphi-based RTL functions like FloatToStr(), Format(), etc. It does not apply to C++-based functions like std::(s)printf(), std::to_string(), std::ostream::operator<<, etc. For those, you need to use C++ locales instead.
I solved it in the wee hours of the morning myself. You can use:
TFormatSettings fmt = TFormatSettings::Create();
fmt.DecimalSeparator = '.';
and then format a double like that:
FloatToStr(price, fmt);
I hope it helps someone. I was going crazy.
I know this this is a very old thread, but I was facing this problem today. In my case, my solution is this:
String DotFormatted(long double value, int numberOfDecimals=2) {
String result = Format("%." + IntToStr(numberOfDecimals) + "f", ARRAYOFCONST((value)));
result = StringReplace( result, ",", ".", TReplaceFlags() << rfReplaceAll);
return result;
}
It's equivalent to another one I had in a different language. For me, it's useful because of the numberOfDecimals argument.
I have to convert string in mm/dd/yyyy format to datetime variable but it should remain in mm/dd/yyyy format.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Please help.
You are looking for the DateTime.Parse() method (MSDN Article)
So you can do:
var dateTime = DateTime.Parse("01/01/2001");
Which will give you a DateTime typed object.
If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)
Which you would use in a situation like this (Where you are using a British style date format):
string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);
You need an uppercase M for the month part.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Lowercase m is for outputting (and parsing) a minute (such as h:mm).
e.g. a full date time string might look like this:
string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");
Notice the uppercase/lowercase mM difference.
Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.
public static class DateTimeMyFormatExtensions
{
public static string ToMyFormatString(this DateTime dt)
{
return dt.ToString("MM/dd/yyyy");
}
}
public static class StringMyDateTimeFormatExtension
{
public static DateTime ParseMyFormatDateTime(this string s)
{
var culture = System.Globalization.CultureInfo.CurrentCulture;
return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
}
}
EXAMPLE: Translating between DateTime/string
DateTime now = DateTime.Now;
string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();
Note that there is NO way to store a custom DateTime format information to use as default as in .NET most string formatting depends on the currently set culture, i.e.
System.Globalization.CultureInfo.CurrentCulture.
The only easy way you can do is to roll a custom extension method.
Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator defined that automatically translates to and from DateTime/string. But that is dangerous territory.
Solution
DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)
I did like this
var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);
You can change the format too by doing this
string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");
// this change the "/" for the "-"
The following works for me.
string strToday = DateTime.Today.ToString("MM/dd/yyyy");
Hi I am working C# MVC project. I have got date like this
string datetime = frmcollection["txtTo"].ToString()
Here datetime variable contains date and time in following format : 06/05/2014 10:25:39
Now I need to above datetime in int, so i replaced all /, :, and space.
So now i have following result :
int datetime = 0;
datetime = intdatetime
so here datetime variable has following reuslts : 6052014102539
So what I need here is, I need to store int time in different format like this : 2014060514102539. so basically i need to rearrange position of inttime.
How can i do this ??
string datetime = frmcollection["txtTo"].ToString();
// your date format that is coming from form collection...
string yourDateFormat = "MM-dd-yyyy HH:mm:ss";
// convert string to date time
DateTime newDate = DateTime.ParseExact(datetime, yourDateFormat, null);
// change its format and convert it to string
string newDateStr = newDate.ToString("yyyy/MM/dd HH:mm:ss");
and use your "string to int" method...
Create a method that takes your string, parses it to a date and returns a weird datetime int. Something like this:
public int ParseDateToWeirdInt(string date)
{
//Error checking omitted
var d = DateTime.Parse(date);
var stringThatWillBecomeAnInt = "";
stringThatWillBecomeAnInt = d.Year.ToString();
stringThatWillBecomeAnInt += d.Month.ToString();
stringThatWillBecomeAnInt += d.Date.ToString();
stringThatWillBecomeAnInt += d.TimeOfDay.Hours.ToString();
stringThatWillBecomeAnInt += d.TimeOfDay.Minutes.ToString();
stringThatWillBecomeAnInt += d.TimeOfDay.Seconds.ToString();
return int.Parse(stringThatWillBecomeAnInt);
}
You should probably use a StringBuilder instead of concatenating the string and a recommendation would be to turn the method into an extension method. Also note that the method needs much better error handling (the date parse could fail, the int parse could fail etc.).
Thanks guys for helping me out. I found this solution as easy for me .
datetime = Convert.ToDateTime(datetime ).ToString("yyyy/dd/MM HH:mm:ss");
so now i have datetime in format i need. Now i can convert to int.
Just adding this answer as a cleaner solution
string datetime = frmcollection["txtTo"].ToString();
string newDateTime;
DateTime theDateTime;
if (DateTime.TryParse(datetime, out theDateTime))
{
newDateTime = theDateTime.ToString("yyyy/dd/MM HH:mm:ss");
}
else
{
// tell user they have entered the date in wrong format
}
How do I convert a float to a string in F#. I'm looking for a function with this signature:
float -> string
As others pointed out, there are a few options. The two simplest are calling ToString method and using string function. There is a subtle difference between the two that you should be aware of. Here is what they do on my system:
> sprintf "%f" 1.2;;
val it : string = "1.200000"
> string 1.2;;
val it : string = "1.2"
> 1.2.ToString();;
val it : string = "1,2"
The first two are different, but both make sense, but why the heck did the last one return "1,2"?
That's because I have Czech regional settings where decimal point is written as comma (doh!) So, the string function uses invariant culture while ToString uses current culture (of a thread). In some weird cultures (like Czech :-)) this can cause troubles! You can also specify this explicitly with the ToString method:
> 1.2.ToString(System.Globalization.CultureInfo.InvariantCulture);;
val it : string = "1.2"
So, the choice of the method will probably depend on how you want to use the string - for presentation, you should respect the OS setting, but for generating portable files, you probably want invariant culture.
> sprintf "%f";;
val it : (float -> string) = <fun:it#8>
Use the 'string' function.
string 6.3f
string;;
val it : (obj -> string) = <fun:it#1>
Just to round out the answers:
(fun (x:float) -> x.ToString())
:)
I am displaying a double to the user, but it is printed as 1.00000000001
However, I need only two digits after the decimal point.
There's a class called Formatter that can do the trick. Here's a code snippet:
double value = 1.24790000001;
Formatter formatter = new Formatter();
String formatted = formatter.formatNumber(value, 2);
And, here's a link to the JavaDoc: javax.microedition.global.Formatter
Have you looked at String.format e.g.
String x = String.format("%.2f", number);
http://download.oracle.com/javase/6/docs/api/java/lang/String.html