I have a weird problem in converting a string to double in .NET 3.5. Here is my code:
dbl = double.Parse(str);
When str is string with a simple double like "5.67" the result for dbl is 567.0.
I'd guess this is localisation issues and you need to use the overload that specifies a format provider.
The issue is likely that it is expecting , as a decimal separator and . as a thousand separator (and thus ignoring it in effect).
Example to reproduce possible issue:
string input = "5.67";
Console.WriteLine(Double.Parse(input, new CultureInfo("en-gb")));
Console.WriteLine(Double.Parse(input, new CultureInfo("de-de")));
This outputs:
5.67
567
I'm just editing Chris's answer:
value = "5.67";
double out;
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
culture = CultureInfo.CreateSpecificCulture("en-GB");
Console.WriteLine(Double.TryParse(value, style, culture, out number)?number:0);
Related
Why does NumberFormat(".##").format(17.46) leads to a string of 17.46 and not .46?
How can I achieve the latter, i.e. remove all digits in front of the decimal sign?
The NumberFormat only changes the way that a number is being displayed(basically, what formatting is). So you can't get the fractional part of the number(it doesn't work like pattern matching).
Instead, you can use:
var num = 17.46;
var fraction = num.toString().split('.')[1];
Note: you can use '.' + num.toString().split('.')[1] to get the fraction part with the starting dot.
You can read more about the ICU Formatting that NumberFormat uses in this link.
Just as an alternative to the other answer, you can try to remove the integer part before converting to String, and not after:
String formatFraction (num a){
num b = a.floor();
num c = a-b;
return NumberFormat(".##").format(c);
}
This way you can guarantee it will work despite of locale.
‘#’ in the NumberFormat class marks a single digit (omitted if the value is zero). So the number of hashtags after the decimal point denotes how many decimal places you want. For example:
double number = 12.1234;
NumberFormat(".#").format(number); //prints 12.1
NumberFormat(".##").format(number); //prints 12.12
NumberFormat(".###").format(number); //prints 12.123
NumberFormat(".####").format(number); //prints 12.1234
You could use substring and indexOf to remove everything before the decimal point, like so:
String str = "12.36";
String newStr = str.substring(str.indexOf('.') + 1);
//If you want to include the decimal point, remove the + 1.
We need to convert a plain number to a currency value. However, nothing we find seems to work.
We tried the basic code below, but that returns a value of $123,456.00 when it should be $1,234.56.
$rawNumber = 123456
$newNumber = 0
$newNumber = "{0:c}" -f $rawNumber
We tried different iterations of "{0:c}" (c2, c1,etc), but it always returns a number, but just adding zeroes on to the end.
We tried converting the number to a string and inserting the decimal, commas and dollar sign, but we're dealing with numbers that can be as short as two or as long as ten, so it becomes something of a beast to try and plan for every possible combination.
Are we missing something obvious to easily convert numbers to a currency value?
Thank you for any help you can provide.
If you have a subdivision of the primary unit of a currency, you need to divide the input value to get the number of primary units, in this case:
$dollars = $rawNumber / 100
$formattedString = '{0:C}' -f $dollars
Beware that the resulting formatted string will depend on the current locale. You can pass a [cultureinfo] object to the ToString() method of the target object instead if you want a specific locale enforced. Here shown with en-US, de-DE and da-DK:
PS C:\> 'en-US','de-DE','da-DK' |ForEach-Object { $dollars.ToString('C',[cultureinfo]$_) }
$1,234.56
1.234,56 €
1.234,56 kr.
You can format the input using {0:C2} the 2 in C2 is the amount of decimal places.
Example:
$rawNumber = 123456
$newNumber = 0
$newNumber = "{0:C2}" -f $rawNumber
I deal with numbers of this form 1.446267186999E7 and i want to represent them without E.
For example 1.446267186999E7 i want it to be 14462671.86999 .
How do i convert it to this form without getting the :
error: integer number too large.
Thanks for the helpers.
Try this:
BigDecimal(1.446267186999E7).toString
The BigDecimal.toString method will give you the string representation of the number in decimal form.
That is just a formatting problem if you store it as a double.
import java.text.DecimalFormat
val d: Double = 1.446267186999E7
val decimalFormat: DecimalFormat = new DecimalFormat("0.#####")
println(decimalFormat.format(d))
should give you 14462671.86999
You probably after BigDecimal. In terms of string formatting, look at the .format method, or printf
I need code for removing all unicode characters in a vb6 string.
If this is UTF-16 text (as normal VB6 String values all are) and you can ignore the issue of surrogate pairs, then this is fairly quick and reasonably concise:
Private Sub DeleteNonAscii(ByRef Text As String)
Dim I As Long
Dim J As Long
Dim Char As String
I = 1
For J = 1 To Len(Text)
Char = Mid$(Text, J, 1)
If (AscW(Char) And &HFFFF&) <= &H7F& Then
Mid$(Text, I, 1) = Char
I = I + 1
End If
Next
Text = Left$(Text, I - 1)
End Sub
This has the workaround for the unfortunate choice VB6 had to make in returning a signed 16-bit integer from the AscW() function. It should have been a Long for symmatry with ChrW$() but it is what it is.
It should beat the pants off any regular expression library in clarity, maintainability, and performance. If better performance is required for truly massive amounts of text then SAFEARRAY or CopyMemory stunts could be used.
Public Shared Function StripUnicodeCharactersFromString(ByVal inputValue As String) As String
Return Regex.Replace(inputValue, "[^\u0000-\u007F]", String.Empty)
End Function
Vb6 - not sure will
sRTF = "\u" & CStr(AscW(char))
work? - You could do this for all char values above 127
StrConv is the command for converting strings.
StrConv Function
Returns a Variant (String) converted as specified.
Syntax
StrConv(string, conversion, LCID)
The StrConv function syntax has these named arguments:
Part Description
string Required. String expression to be converted.
conversion Required. Integer. The sum of values specifying the type of conversion to perform. `128` is Unicode to local code page (or whatever the optional LCID is)
LCID Optional. The LocaleID, if different than the system LocaleID. (The system LocaleID is the default.)
I have a gtk.spinbutton and I want to set the digits according to the locale
format.
like say I have a locale installed hungarian so my decimal separator is
'.'(dot) and thousand separator is ','(comma) eg: my spinbutton value is
1131191 so after the user focus out of the gtk.spinbutton my value should
convert to 11,311.91 . the conversion is made by me but I am not able to set
it to gtk.spinbutton either using set_text / set_value method.
Any help is appreciated !
Thanks
Formatting a SpinButton can be done by handling the output signal.
locale.setlocale(locale.LC_ALL, '')
def output(spin):
digits = int(spin.props.digits)
value = spin.props.value
text = locale.format('%.*f', (digits, value), True)
spin.props.text = text
return True
spin.connect('output', output)
If you also want to let users enter values in the localised format (e.g. let the user type "1,000" instead of "1000"), handle the input signal.
def input(spin, new_value):
text = spin.props.text
try:
value = locale.atof(text)
except ValueError:
return -1
p = ctypes.c_double.from_address(hash(new_value))
p.value = value
return True
spin.connect('input', input)
(This code is longer than it should be because PyGTK does not properly wrap input, hence the ctypes hack. It's just parsing the text and then assigning the numeric value to a pointer location.)
Credits: The ctypes hack and digits formatting are inspired by Tim Evans's post in the PyGTK mailing list.