C# Convert string to double/decimal and back to string, keeping trailing zeroes, adding comas for thousands
double.Parse(input)
is a no go, as double
does not keep track of the number of decimals.
decimal.Parse(input).ToString()
will show that decimal
does keep track of that. Unfortunately, decimal.Parse(input).ToString()
uses this precision and doesn't use a thousands separator, and decimal.Parse(input).ToString("N")
ignores the precision but does use a thousands separator.
Manually extracting the precision from the decimal works though, and that allows you to build the correct format string:
static string InsertThousandsSeparator(string input) {
var dec = decimal.Parse(input);
var bits = decimal.GetBits(dec);
var prec = bits[3] >> 16 & 255;
return dec.ToString("N" + prec);
}
This is based on the layout of decimal
as described on MSDN:
Bits 16 to 23 must contain an exponent between 0 and 28, which indicates the power of 10 to divide the integer number.
See it working on .NET Fiddle. (courtesy of @Alisson)
How do I convert a string to a decimal number in c#
decimal.Parse is best in your case
Convert string value into decimal with proper decimal points
As already commented 11.1
is the same value as 11.10
decimal one=11.1;
decimal two=11.10;
Console.WriteLine(one == two);
Will output true
The #
formatter in the to string method means an optional digit and will supress if it is zero (and it is valid to suppress - the 0
in 4.05
wouldn't be suppressed). Try
decinum.ToString("0.00");
And you will see the string value of 11.10
Ideally you actually want to use something like
string input="11.10";
decimal result;
if (decimal.TryParse(input,out result)) {
Console.WriteLine(result == 11.10);
} else {
// The string wasn't a decimal so do something like throw an error.
}
At the end of the above code, result will be the decimal you want and "true" will be output to the console.
How can I parse a string as an integer and keep decimal places if they are zeros?
Your premise is flawed. If you parse a number, you are converting it to its numerical representation, which by definition doesn't have trailing zeros.
A further flaw is that you seem to think you can multiply two numbers together and keep the same number of decimal places as the original numbers. That barely makes sense.
It sounds like this might be an XY Problem, and what you really want to do is just have two decimal places in your result.
If so, you can use .toFixed()
for this:
var num = parseFloat("59.50");var num2 = parseFloat("12.33");var num3 = num * num2
console.log(num3.toFixed(2)); // 733.64
How to convert strings to numbers in python while preserving fractional parts
Integers are only numbers that have no decimals.
-4,-3,-2,-1,0,1,2,3,4,...,65535 etc...
Floating point numbers or Decimal numbers are allowed to represent fractions and more precise numbers
10.5, 4.9999999
If you want to take a string and get a numerical type for non-whole numbers, use float()
float('10.5')
Here is a very simple elementary school explanation of integers
Here is the python documentation of numerical types
Conversion of Binary fractions to Decimal in C# GUI
It's just a typo in your code:
finAns = (val2 + val2).ToString();
should be
finAns = (val1 + val2).ToString();
Note that val2 was added to val2 rather than val1 being added to val2.
Related Topics
Performance of Nested Yield in a Tree
Check If a Property Exists in a Class
Is There Any Performance Difference Between ++I and I++ in C#
Catching Unhandled Exception on Separate Threads
Regex: Repeated Capturing Groups
C# Linq Where Date Between 2 Dates
Parsing HTML to Get Content Using C#
Changing the View for a Viewmodel
Implementing the Producer/Consumer Pattern in C#
How to Determine If an Event Is Already Subscribed
Binary to Corresponding Ascii String Conversion
Getting Hwnd Off of Corewindow Object in Uwp
Static and Instance Methods with the Same Name
How to Check If a String Is a Number
How to Cast Expression<Func<T, Datetime>> to Expression<Func<T, Object>>