I have written one program,it use float variables and after calculate some functions it doesn’t have sufficient precise result.
my program is
int x=0;
ts_sec = 1338526801;
ts_usec = 113676;
while(ir<2)
{
Console.Write("ts_sec:" + ts_sec+"\t");
Console.Write("ts_usec:" + ts_usec+"\t");
if (x == 0)
{
floatstart = ts_sec + ts_usec / 1000000;
Console.Write("startTime" + floatstart+"\t");
x=x+1; //x=1
}
timeStamp = ts_sec + ts_usec / 1000000 - floatstart; //
Console.Write("timestamp is" + timeStamp+"\n");
ts_sec = 1338526801;
ts_usec = 113676;
ir++;
}
this is my out put:
ts_sec:1338526801 ts_usec:113676 startTime1.338527E+09
timestamp is0 ts_sec:1338526801 ts_usec:113678
timestamp is0
but I want my output will be like this and I want my result doesn’t have E .
ts_sec:1338526801 ts_usec:113676 startTime:1338526801.11368
timeStamp:0 ts_sec:1338526801 ts_usec:113678
timeStamp:1.9073486328125e-006
First, change float (32-bit) to double (64-bit) to increase precision nearly two times; second if you don't want the result being in scientific representation (i.e. with "e") choose appropriate formatting:
Double startTime = ...
// Assuming that you want 5 digits after the decimal point
String result = startTime.ToString("F5");
If you want more precision use decimal.
The decimal keyword indicates a 128-bit data type. Compared to floating-point types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations.
Related
I'm trying to make a calculator that calculates Lorentz factor in c#. But it doesn't seem to work with decimals. I've only done the first part of the calculator:
static void Main(string[] args)
{
int c = 299792458;
Console.Write("speed: ");
string speed = Console.ReadLine();
Console.Write("Gammafaktor: ");
string Gammafaktor = Console.ReadLine();
{
}
int gamma1 = Convert.ToInt32(Gammafaktor);
int speed1 = Convert.ToInt32(speed);
if (gamma1 != 0)
{
Console.WriteLine(1 / (Math.Sqrt(1 - ((speed1 * speed1) / (1)))));
}
}
}
}
If you want to calculate with decimals, then you need to use Double data type instead of an Integer.
An int has a range from -2,147,483,648 to 2,147,483,647 and a double has a range from +-5.0 x 10-324 to +-1.7 x 10308.
You see that a int can't handle decimals.
If the factor of your number would be high, I advice you to use Decimal
Decimals have much higher precision and are usually used within monetary (financial) applications that require a high degree of accuracy.
Reference
Besides lorenz factor uses 1 / sqrt(1 - v*v)
var calc = 1m / Convert.ToDecimal(Math.Sqrt(1 - speed1*speed1));
When you divide by 1 instead of c under the square root, this means that you measure speed in units of c, not in m/s. Consequently, the numerical value of velocity must be a fraction of 1.
However, your variable speed1 is an integer.
I need to get the net values (vat #20%) of wallet and paper as below, added together
{
this.transaction.netValue = Math.Round(Convert.ToDecimal(wallet) + Convert.ToDecimal(paper), 2);
}
and then to get the vat value (20%) having established the net values of both wallet and paper
{
transaction.vatAmount = Round(Convert.ToDecimal(wallet) + Convert.ToDecimal(paper), 2);
}
I know how to do the formulas in excel, but having difficulty in c#
Updated
this.transaction.netValue = Math.Round(Convert.ToDecimal([wallet]/1.2m) + Convert.ToDecimal([paper]/1.2m), 2);
Convert to decimal first then divide by 1.2m
You are seeing squiggly lines because your are trying to divide two different types of datatypes. first your're converting wallet to decimal and then you're dividing it with 1.2 which is double and you need to change it to decimal as well. From decimal (C# Reference)
If you want a numeric real literal to be treated as decimal, use the
suffix m or M. Without the suffix m, the number is treated as a double
and generates a compiler error.
So your final code will be something as follows
this.transaction.netValue = Math.Round(Convert.ToDecimal(wallet) / 1.2m + Convert.ToDecimal(paper) / 1.2m, 2);
Assuming that the values in wallet and paper strings are actually valid decimal numbers then you need to apply
decimal totalValue = Convert.ToDecimal(wallet) +
Convert.ToDecimal(paper);
decimal netValue = totalValue / 1.2m;
this.transaction.netValue = Math.Round(netValue, 2);
Do not put square brackets around the string and do not put the division inside the parameter (a string is required) that you pass to Convert.ToDecimal
Of course this could be written in a single line but because you are recalculating again that netValue for vatAmount then using a temporary variable is better because you can reuse it for the subsequent calculation
(By the way vatAmount = totalValue - netValue, right? )
Instead if your inputs are not guaranteed to be correct decimal values then you should use decimal.TryParse
decimal walletValue;
decimal paperValue;
if(!decimal.TryParse(wallet, out walletValue))
{
MessageBox.Show("Not a valid decimal value for wallet");
return;
}
if(!decimal.TryParse(paper, out paperValue))
{
MessageBox.Show("Not a valid decimal value for paper");
return;
}
decimal totalValue = walletValue + paperValue;
decimal netValue = totalValue / 1.2m;
this.transaction.netValue = Math.Round(netValue, 2);
this.transaction.vatValue = Math.Round(totalValue - vatValue, 2);
My scenario is that if
47/15= 3.13333
i want to convert it into 4, if the result has decimal i want to increase the result by 1, right now i am doing this like
float res = ((float)(62-15) / 15);
if (res.ToString().Contains("."))
{
string digit=res.ToString().Substring(0, res.ToString().IndexOf('.'));
int incrementDigit=Convert.ToInt16(k) + 1;
}
I want to know is there any shortcut way or built in function in c# so that i can do this fast without implementing string functions.
Thanks a lot.
Do you mean you want to perform integer division, but always rounding up? I suspect you want:
public static int DivideByFifteenRoundingUp(int value) {
return (value + 14) / 15;
}
This avoids using floating point arithmetic at all - it just allows any value which isn't an exact multiple of 15 to be rounded up, due to the way that integer arithmetic truncates towards zero.
Note that this does not work for negative input - for example, if you passed in -15 this would return 0. you could fix this with:
public static int DivideByFifteenRoundingUp(int value) {
return value < 0 ? value / 15 : (value + 14) / 15;
}
Use Math.Ceiling Quoting MSDN:
Returns the smallest integral value that is greater than or equal to
the specified decimal number.
You are looking for Math.Ceiling().
Convert the value you have to a Decimal or Double and the result of that method is what you need. Like:
double number = ((double)(62-15) / (double)15);
double result = Math.Ceiling(number);
Note the fact that I cast 15 to a double, so I avoid integer division. That is most likely not what you want here.
Another way of doing what you ask is to add 0.5 to every number, then floor it (truncate the decimal places). I'm afraid I don't have access to a C# compiler right now to confirm the exact function calls!
NB: But as others have confirmed, I would think the Math.Ceiling function best communicates to others what you intend.
Something like:
float res = ((float)(62-15) / 15);
int incrementDigit = (int)Math.Ceiling(res);
or
int incrementDigit = (int)(res + 0.5f);
let suppose dis.text = 2, prc.text = 100, I am using these codes.It Should be
net_prc.text = 98.But its giving me -100.Can anybody tell me why?,And how can i get correct
discounted percentage??
private void net_prcTabChanged(object sender, EventArgs e)
{
int d;
int di;
int i;
d = Convert.ToInt32(dis.Text);
i = Convert.ToInt32(prc.Text);
di = -((d / 100) * i) + i;
net_prc.Text = di.ToString();
}
Try (d / 100.0) to force it to use floating point arithmetic
di = -((d / 100) * i) + i;
All values in this statement are Integers. You are going to be computing arithmetic with decimal places, and you need to increase the precision of your variables to a double or a float. Instead, add a decimal place to one of the values in the equation. This will force all values into doubles.
This is a process called Arithmetic Promotion. It is where, at run time, the precision of every variable in an equation is increased to the size of the most precise variable.
Proper way to do it would be, changing the datatype of di to float
di = (d * 100) / i;
C# has an odd way of doing maths, because your numbers are cast as integers, you can only do integer math with them. you need to initially have them as float or as double so you can do float math or anything at all that requires a decimal place within the calculations.
Even dis.text = 1.5
private void net_prcTabChanged(object sender, EventArgs e)
{
double d;
double di;
double i;
d = Convert.ToDouble(dis.Text);
i = Convert.ToDouble(prc.Text);
di = -((d * 100.0) / i ) + i;
net_prc.Text = di.ToString();
}
Your division, d / 100, is a division of integers, and it returns an integer, probably 0 (zero). This is certainly the case with your example d = 2.
Addition: If you really want to do this with integers (rather than changing to decimal or double like many other answers recommend), consider changing the sub-expression
((d / 100) * i)
into
((d * i) / 100)
because it will give you a better precision to do the division as the last operation. With the numbers of your example, d=2 and i=100, the first sub-expression will give 0*100 or 0, while the changed sub-expression yields 200/100 which will be 2. However, you will not get rounding to nearest integer; instead you will get truncating (fractional part is discarded no matter if it's close to 1).
I want a function that is passed an integer, and if that integer is over a certain value (1000 in my current case) I want to perform some division on it so I can ultimately return an abbreviation of the original integer.
For example:
1000 = 1
1001 = 1
1099 = 1
1100 = 1.1
1199 = 1.1
1200 = 1.2
10000 = 10
10099 = 10
10100 = 10.1
It's the division and rounding side of things that has been causing me problems.
What would be the most suitable method to give me the results above?
How about:
int dividedBy100 = x / 100; // Deliberately an integer division
decimal dividedBy1000 = dividedBy100 / 10m; // Decimal division
string result = dividedBy1000.ToString();
I would advise using decimal here rather than float or double, as you fundamentally want decimal division by 10.
An abbreviation is by definition rounded.
If you are looking for more precision why not use Double instead of Integer?
Here's a suggestion
double function(int number)
{
if (number >= 1000)
{
return (((double)number) / 1000);
}
}
Your examples seem to imply that you only want one decimal place of precision, so how about something like this:
Divide by 100
Cast to double (or float)
Divide by 10
The first division will truncate any trailing numbers less than 100 (the equivalent of a 100-base floor function), then casting to double and dividing by 10 will give you the single decimal place of precision you want.
if t is the original number, then
int a=t/100
float b=a/10
b should contain your answer
Some more code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
while (true)
{
string s;
s = Console.ReadLine();
int a = Convert.ToInt32(s);
a = a / 100;
float b = a / (float)10.0;
Console.WriteLine(b);
}
}
}
}
You should use modular (remainder) mathematics to do this. You don't need to involve the FPU (Floating Point Unit).
static string RoundAndToString(int value, int denominator)
{
var remainder = value % denominator;
value = (value - remainder) / denominator;
if (remainder == 0)
return value.ToString();
remainder = (remainder * 10) / denominator;
return string.Format("{0}{1}{2}", value, CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, remainder);
}
Since you just want to truncate the number, it makes sense to convert it to a string, remove the last two characters from the string, then divide by 10 to get the corresponding number.
Here is the algorithm in Ruby. (I don't have C# handy)
a = 1000 #sample number
-> 1000
b = a.to_s[0..-3] #a converted to a string, then taking all characters except the last two.
-> "10"
c = b.to_i / 10.0 # converts to float in correct power
-> 1.0
You then display "c" in whatever format you want using sprintf (or the C# equivalent using FormatNumber).
try
int MyNumber = 10100;
string MyString = ((int) MyNumber/1000).ToString() + (( MyNumber % 1000) > 99 ? "." + (((int)( MyNumber / 100 )) % 10).ToString() : "");