limit double at six decimal place in asp.net - asp.net

i have a double, the decimal place isn't fix (8-?)
i want to fix the decimal place to six (for example: 1,234567).
this is my double:
CStr(score)
i guess it's quiet simple :P

Try this instead:
score.ToString("0.000000")

You can also Math.Round(3.44, 1) 'Returns 3.4.
Math.Round

After Decimal point Add Zero's like this
Dim tot as String
Dim totAmt as Double
totAmt=10.10
tot=String.Format("{0:00.000}", totAmt)
OutPut: 10.100
After Decimal point Remove Zero's like this
totAmt=10.750
tot=Math.Round(totAmt,2)
Output:10.75
Sloved

Related

Flex NumericStepper: limit range of integer part before the decimal point

I have a NumericStepper in flex that must accept values between 0 and 999.99.
I tried setting the numericStepper as follows:
<s:NumericStepper id="numStepper" value="#{myValue}" maximum="999.99" snapInterval="0.01" stepSize="0.01" minimum="0"/>
and setting also a NumberValidator attached to it:
var nValidator:NumberValidator = new NumberValidator();
nValidator.source = numStepper;
nValidator.precision = 2;
numericStepper.maxChars=6;
nValidator.decimalSeparator=".";
The thing works but I would like also to directly limit the user input via keyboard in the numeric stepper, so that the user can't type things like "1.4567" but only 1.45.
So I want something to limit the integer and decimal part of the number according to my specifications:
max 3 chars integer part
"." decimal separator
max 2 chars precision
Maybe some regular expression can help?
Thanks
Have you tried...
nValidator.fractionalDigits = 2;

How to convert string to int?

How to convert string to int?I know convert.ToInt32 is used.But it fail.Error is input string is not in proper format.
String s1 = "12.00"
I love the assumption that the decimal separator always is a dot (.). You'd better use the InvariantCulture, which contains a NumberFormat that explicitly specifies the dot as a decimal separator:
Convert.ToInt32(Convert.ToDouble("12.00", CultureInfo.InvariantCulture));
To clarify: half the world uses the dot, the other half a comma. When I run this on a PC with a Dutch culture and do not specify a CultureInfo, it takes the system default (comma) and returns 1200, ignoring the dot.
While it does not directly affect your problem, it is something that can't be stressed enough.
error is because string is "12.00"
first convert string to double than in int
int a = Convert.ToInt32(Convert.ToDouble("12.00"));
or
IF you just want integer part of it than
string s= "12.00";
string[] words = s.Split('.');
int a = Convert.ToInt32(words[0]);
Also check already answered threads on SO : C# Convert String Decimal to Int
"12.00" is a decimal number, not an integer. Integers don't have fractional portions. Use Convert.ToDouble or similar to get a floating-point number, or trim off the decimal part of the string (the . and what follows) prior to calling Convert.ToInt32.
The string "12.00" is a double/decimal value. Use Double.Parse() or Double.TryParse() or Convert.ToDouble().

Replace string from character onwards

I've got a string like so
Jamie(123)
And I'm trying to just show Jamie without the brackets etc
All the names are different lengths so I was wondering if there was a simple way of replacing everything from the first bracket onwards?
Some others are displayed like this
Tom(Test(123))
Jack ((4u72))
I've got a simple replace of the bracket at the moment like this
mystring.Replace("(", "").Replace(")","")
Any help would be appreciated
Thanks
VB.NET
mystring.Substring(0, mystring.IndexOf("("C)).Trim()
C#
mystring.Substring(0, mystring.IndexOf('(')).Trim();
One logic; get the index of the ( and you can trim the later part from that position.
public static string Remove(string value)
{
int pos = value.IndexOf("(");
if (pos >= 0)
{
return value.Remove(pos, remove.Length);
}
return value;
}
aneal's will work. The alternative I generally use because it's a bit more flexible is .substring.
string newstring = oldstring.substring(0,oldstring.indexof("("));
If you aren't sure that oldstring will have a "(" you will have to do the test first just as aneal shows in their answer.
String.Remove(Int32) will do what you need:
Deletes all the characters from this string beginning at a
specified position and continuing through the last position.
You will also have to .Trim() as well given the data with padding:
mystring = mystring.Remove(mystring.IndexOf("("C))).Trim()

Convert unicode digits from english to devanagari

I was looking for some RegEx or any other method to convert digits 0-9 into ०-९ (devanagari script). I am using asp.net but could not find any method in globalization namespace which does this.
Any help is greatly appreciated.
Found similar post here!
My solution is bit different though as I know the source and destination culture. So I can hard-code the digits array.
string devYear = "";
string[] devD = { "०", "१", "२", "३", "४", "५", "६", "७", "८", "९" };
char[] digits = curYear.ToCharArray();
foreach (char ch in digits)
{
devYear += devD[int.Parse(ch.ToString())];
}
Another change is that I am iterating through the year digits instead of devD array. Saves few iterations as most numbers will be less than 10 digit. In my case, only four digits.
Hopefully will be useful for someone stuck up on similar lines.
Does each latin digit 0..9 map to exactly a devanagari digit (I do think so, if I understand Wikipedia correctly)=
If yes, how about the following:
public static string ConvertDigits( string s )
{
return s
.Replace("0", "०")
.Replace("1", "१")
.Replace("2", "२")
.Replace("3", "३")
.Replace("4", "४")
.Replace("5", "५")
.Replace("6", "६")
.Replace("7", "७")
.Replace("8", "८")
.Replace("9", "९");
}
For optimization, you could check for string.IsNullOrEmpty() before calling the string.Replace function.
In Addition (if this is suitable for a devanagari digit), call the string.Replace() function overload that takes chars as parameters rather than strings.

Accounting Style string format in ASP.NET

I would like to know the easiest way to format a string as accounting style. I know how to format as currency using {0:c} but there are some differences in accounting style, for example, all the dollar signs will line up as well as all the decimal points, and negatives are expressed in parenthesis rather than with a "-" minus sign. You can find a good example of the way i would like it in excel if you format the cells as "accounting" with 2 decimal places.
Ignoring your alignment requirements, you could use
number.ToString("€#,##0.00;(€#,##0.00);Zero")
to bracket negative numbers.
To align your numbers, you'd have to format without the currency symbol, and pad the formatted numbers yourself with spaces, using a fixed width font would make this job easier for you.
EDIT:
It seems String.Format is your friend:
String.Format("{0,15:#,##0.00 ;(#,##0.00);- }", number)
where 15 is the total width of the output, and you need to append this text to your currency symbol. (Again, this aligns in fixed width only)
There's no format string shortcut (the single-character ones with default rules) for handling accounting style formats (here's a cheat sheet with the available format strings) so you'll have to write a more specific one (like Patrick's answer) or your own parsing method.
The alignment requirements would be specific to how you're displaying them. I'm assuming you are using a table, in which case you're limited by what HTML supports, and it doesn't support accounting style alignments like Excel.
In this blog there were some various formats outlined and this one seemed to be close to what you were looking for:
int neg = -10;
int pos = 10;
// C or c (Currency): It represent how many decimal place of zeros to show.
String.Format("{0:C4}", pos); //"$10.0000"
String.Format("{0:C4}", neg); //"($10.0000)"
It doesn't handle the padding (you may have to fix that yourself), but it does have the proper parenthesis.
You could do something using a variation of Patricks method. This will handle formating and alignment assuming you know the upper bound of how large a value you are dealing with:
private static string OutputAsCur(decimal val)
{
string format = " #,##0.00 ; (#,##0.00);Zero";
string frmt = val.ToString(format);
return CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol + frmt.PadLeft(15, ' ');
}
Here's a simple example app to see it format:
static void Main(string[] args)
{
decimal d = 155.55m;
Console.WriteLine(OutputAsCur(d));
Console.WriteLine(OutputAsCur(d * -1));
Console.WriteLine(OutputAsCur(1002.32m));
Console.WriteLine(OutputAsCur(1002.32m * -1));
Console.ReadLine();
}
You can use a format string for String.Format to get what you're trying to accomplish. The only trick is that positive numbers, since they will not have a closing parenthesis mark, will have to incorporate a space at the end if they will be aligned with any negative numbers that will be in the column. The trick is to get that space into the string in a way that HTML will not ignore. I simply use the HTML entity which indicates a non-breaking space in HTML.
Here's sample code. First, in the aspx.
<table>
...
<tr>
<th scope="row" colspan="2">Total Revenue</th>
<td class="numeric total"><asp:Label runat="server" ID="TotalRevenueLabel" /></td>
</tr>
...
</table>
Now, the codebehind.
public const string kMoneyFormat = "#,#.00' ';(#,#.00);'-.-- '";
public void DataBind()
{
using (FinancialDataContext sql = new FinancialDataContext())
{
var periodQuery = from m in sql.Forecasts()
select m;
ForecastsResult periodData = periodQuery.Single();
decimal totalRevenue = period.Data.income_actual.Value + periodData.other_income.Value;
TotalRevenueLabel.Text = totalRevenue.ToString(kMoneyFormat);
}
}
I followed these steps for apply the "Accounting" format.
In a new Book on Excel, select a cell.
Insert data (i.e any number; for this example, add 80000).
Select (Accounting) NumberFormat as is shown in the screenshot #1:
Screenshot #1:
Select "More Number Formats".
Select "Custom".
Select any of the pre-defined formulas (see screenshot #2).
Screenshot #2:
In my case, this is the desired format for this number.
The negative side of this is that when you select the cell with the format applied on it, you wont see selected (Accounting) "in the DropDownList" Number Format.

Resources