You can't. The FLOAT and DOUBLE types represent approximate numeric data values. They are stored in such a way that they can contain a wide range of numbers (from very big to very small), but at the cost of being a bit inaccurate. See Floating point types for more information....

android,string,if-statement,double

try this String text = "your string"; // example double value = Double.parseDouble(text); hope it helps ...

c,int,double,type-conversion,math.h

The trigonometric functions in math.h use radians, not degrees. You can convert the radians to degrees by multiplying by 180 / pi, ( 57.29577951308232). acos(0.13) would return 1.440427347091751 radians which multiplied by 57.29577951308232 gives the result of 82.53040768358306 degrees....

Something like: timeval to_timeval(double usec) { return { usec / 1000000, usec % 1000000 }; } ...

java,swing,jpanel,double,graphics2d

x1 = 43.12929, x2 = 43.12976, y1 = -77.626956, y2 = -77.62679 These y values are outside the panel. AWT/Swing component visible coordinate space runs from (0, 0) to (width-1, height-1). Check where you are computing the values. If you want (0, 0) to be the center, you need to do some...

In your code, change scanf("%lf \n", &radius); to scanf("%lf", &radius); Otherwise, with a format string having whitespace, scanf() will behave as below (quoted from C11, chapter §7.21.6.2, paragraph 5) A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or...

From The "#" Custom Specifier Note that this specifier never displays a zero that is not a significant digit, even if zero is the only digit in the string. It will display zero only if it is a significant digit in the number that is being displayed. If you wanna...

Simply do this, double doubleValue=4.1; String.format(Locale.ROOT, "%.2f", doubleValue ); Output: 4.10 Using this approach you don't need to make use of DecimalFormat which will also reduce unnecessary imports...

ruby-on-rails,double,range,digit

You could add something like this: "%02d" % number It will return for example "%02d" % 1 => "01" "%02d" % 51 => "51" For your example it could be: <%= f.select :credit, (0..500).map { |i| "%03d" % i } %> ...

There's no built in function that I know of. A regular expression can catch it pretty easy, ^\d+(\.\d*)?$ (will match '0.123', but not '.123'). But here's another alternative strategy. <?php function isDigit($var) { return ((string)$var == (float)$var); } var_export(isDigit('123.3')); // true var_export(isDigit('-321')); // true var_export(isDigit('0xFFF')); // false UPDATE: I just...

asp.net-mvc,double,data-annotations

I just fixed the problem i just removed the remote annotation on the lastName, the functionality is still the same but the second error was removed. I thought i had to add the same annotation on the second field to be validated too.

You passed the wrong pattern to DecimalFormat. Change "#.000" to "0.000" can solve your problem. The leading zeroes are not shown if you use "#". Here is the document of DecimalFormat, please refer to the part of Special Pattern Characters....

android,textview,integer,double

double num; //eg 9.00 or 8.75 long beforeDecimal = (long)num; double afterDecimal = num - beforeDecimal; if(afterDecimal>0) display num; else display beforeDecimal; ...

c++,stream,printf,double,stringstream

A couple of comments have mentioned std::setfill('0') and std::setw. While these are necessary, they're not sufficient to the task. For example, this code: std::cout << std::setfill('0') << std::setw(7) << std::showpos << 0.012; will produce: 0+0.012 as its output. This is obviously not quite what we wanted. We need to add...

validation,jsf,double,classcastexception,composite-component

I can't reproduce your problem. It works for me with Mojarra 2.2.10 on Tomcat 8.0.21 even without explicit type attribute in <cc:attribute type="java.lang.Double">. As a workaround you could explicitly declare a converter as below in composite's input component: <p:inputText ... converter="javax.faces.Double"> But Mojarra 2.1.7 is really old (Feb 2012). You...

To specify that a number is a float is must end with an F or f so the code would read: float earthWeight = 195.0f; float moonWeight = earthWeight * .17f; ...

ios,string,swift,double,downcasting

You can simply use variable interpolation in a string with Swift. First get your price and then just use it in a string with the $ prepended- var stockValueString="" if let price=dataArray[0]["stockPrice"] { stockValueString="$\(price)" } Also, note by (strong) convention variable should start with a lower-case letter. Class names start...

Matlab automatically pulls some common factor out numerical vectors, which has confused me many times myself. The line that gives the common factor is easy to miss, especially for large vectors, because it is displayed at the top. If I define a vector with the two number you gave, Matlab...

If you take the example 3 you would see that the result is actually 3.0000000000000009. The problem is in the rounding of a double. If you change the data type decimal the problem is fixed: Sub Main() Dim i As Decimal = 2 For x As Integer = 1 To...

interest is an int so this line interest / 100 is doing integer division, and will always be 0. The quick fix would be to change the literal so you are doing floating point math sum += sum*(interest / 100.0); ...

php,regex,double,double-quotes

Your question is a bit confusing so let me describe what your regular expression does: preg_match('/[^a-zA-Z0-9 \"\'\?\-]/', $v) It will match any string which DOES NOT contain a-zA-Z0-9 \"\'\?\- Also you are escaping your " with \" which is not necessary. Try removing the back slash. The input test" should...

Since float can hold an integer but not vice versa. Just read the data like a float and check if it is an integer using something like if(ceilf(f) == f) { i=(int)f; } //Here i is an integer and f is the float you read using %f To see more...

It sounds like you are linking against a version of printf that does not have floating point support. This is often the default configuration for compilers for embedded systems, because they don't have hardware FPUs and software floating point support uses precious space which most applications don't need. Consult the...

str2double does what you expect. Type whos news or class(news) and you'll see the variable news is of type double: >> class(news) ans = double (You could use str2num to obtain the same result: news = str2num(s); also returns a double.) The fact that you see >> news = 128...

c,binary,double,bit-manipulation,arc4random

When I print the binary representations of i and *(&i+1) and compare them to the binary representation of d, d is composed by appending *(&i+1) and i. So *(&i+1) comes first?! Why is this the case? the actual ordering of the bytes depends upon the 'Endian-ness' of the underlying...

postgresql,double,precision,numeric,to-char

The reason is that for the purpose of the equality comparison, the type with the higher resolution is cast to the type of the lower resolution. I.e.: in the example the numeric is cast to double precision. Demo: SELECT * , num = dp AS no_cast , num::float8 = dp...

double,bit-manipulation,point,floating

I agree with the comment that it should be done in binary, rather than by conversion to decimal and decimal multiplication. I used Exploring Binary to do the arithmetic. The first step is to find the actual binary significands. Neither input is subnormal, so they are 1.000101 and 1.00100001. Multiply...

There is nothing wrong with the >=, your problem is that 1 is not really one. Try this Ax >= 1 [1] FALSE Ax == 1 [1] FALSE and format(Ax, digits = 20) [1] "0.99999999999999977796" Edit: A possible Solution As solutions to your problems you can return the final result...

It's one of the many ways of specifying a double literal, without it 1 would be an integer, which would mean you'd be doing integer division, not double division... System.out.println(1 / 3); // ==> 0 <== Uh oh, integer division System.out.println(1. / 3); // ==> 0.333333 System.out.println(1.0 / 3); //...

arrays,matlab,matrix,double,cell

I think you want to do something like the following. I use a numeric array of size 5 x 5 to demonstrate but that's the same idea in your case. clear clc TX = {'a' 'b' 'c'}; NM = magic(5); %// To generalize; n = numel(TX); NumRowCol = size(NM,1); %///...

drawRect in inherited from Graphics which uses int to specify the co-ords & size. The Graphics2D object on the other hand, is capable of dealing with graphics values that lie 'between whole pixels'. To compensate it will typically render a dithered pixel (part way between the drawing and BG color)...

You use .equals(otherObject) when comparing objects. You're comparing Double which is an object. If you were using double instead, a primitive, you could use == to compare values. Alternatively, get the double value from Double object: if (yourDoubleObject.doubleValue() == otherDoubleObject.doubleValue()) { // Do some things } ...

java,double,override,long-integer,hashcode

The double value is 64 bits wide but the int returned by hash method has only 32 bit. In order to achieve a better distribution of hash values (compared to simply striping the upper 32 bits). The code uses XOR to incorporate the upper 32 bits (containing sign, exponent and...

swift,variables,double,multiplying

You can only multiple two of the same data type. var billBeforeTax = 100 // Interpreted as an Integer var taxPercentage = 0.12 // Interpreted as a Double var tax = billBeforeTax * taxPercentage // Integer * Double = error If you declare billBeforeTax like so.. var billBeforeTax = 100.0...

The easiest way is to create a DecimalFormat object, supplying the pattern yourself. The 0 characters indicate that a digit should be printed here, even if normally unnecessary. DecimalFormat df = new DecimalFormat("0000000000.00"); String formatted = df.format(-2.34); Outputting: -0000000002.34 With String.format, you can supply the total length as well as...

c,floating-point,double,double-precision

Double are represented as m*2^e where m is the mantissa and e is the exponent. Doubles have 11 bits for the exponent. Since the exponent can be negative there is an offset of 1023. That means that the real calculation is m*2^(e-1023). The largest 11 bit number is 2047. The...

In your activity that accepts the input from the EditText: double value = Double.parseDouble(yourEditText.getText().toString()); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (adding) { value = prefs.getFloat("your.float.key", 0f) + value; } else { value = prefs.getFloat("your.float.key", 0f) - value; } SharedPreferences.Editor editor = prefs.edit(); editor.putFloat("your.float.key", value); editor.apply(); In your activity that shows the...

Change printf ("The number of miles per gallon is:%d",dailyDrivingCost(a,b,c)); ^ to printf ("The number of miles per gallon is:%f",dailyDrivingCost(a,b,c)); d conversion specifier is used to print an int, to print a double (or a float) you need the f conversion specifier....

The output is zero because double has a limited percision, and if you multiply a number lower than 1 by itself enough times, you'll get a result too small to be distinguished from 0. If you print d after each iteration, you'll see that it becomes 0 quite fast :...

c#,parsing,double,cultureinfo,currentculture

On my machine the following throws a FormatException, as expected: var number ="10,10"; double value = double.Parse(number, NumberStyles.Float, CultureInfo.InvariantCulture); I suspect you're using NumberStyles.AllowThousands. For example, the following will return 1010: var number ="10,10"; double value = double.Parse(number, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture); UPDATE in response to comment: ... but if...

c++,c++11,random,double,double-precision

The maximum value dist(engine) in your code can return is std::nextafter(1, 0). Assuming IEEE-754 binary64 format for double, this number is 0.99999999999999988897769753748434595763683319091796875 If your compiler rounds floating point literals to the nearest representable value, then this is also the value you actually get when you write 0.99999999999999994 in code (the...

ios,objective-c,methods,double,nsdecimalnumber

numberWithDouble: method of NSDecimalNumber returns NSNumber. In your method you want to return decimal so its OK if you allocate a new NSDecimalNumber with the decimal value (amount in your example). May use the following way to get rid of the error: -(NSDecimalNumber *)myMethod { double amount = 42; ......

java,arrays,string,loops,double

The problem is you are not actually reading anything from the file. You do all the setup but you aren't reading. So when you have: File file = new File(name); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); StringBuffer stringBuffer = new StringBuffer(); String newString = stringBuffer.toString(); Here...

vb.net,datagridview,double,value-type

Use the CellFormatting event to show your currency: Private Sub InventoryDataGridView_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles InventoryDataGridView.CellFormatting If (e.ColumnIndex = 2) Then e.Value = String.Format("{0:$0.00}", e.Value) e.FormattingApplied = True End If End Sub ...

Use format bank to get 2 decimal displayed. More details about the format function in the documentation. If you want to change how the variables are displayed in the variable editor, have a look at this page of the documentation. ...

While I don't think that keeping trailing zeros is necessary, I think this is what you are asking for: DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); java.text.DecimalFormat df = new java.text.DecimalFormat(); df.setDecimalFormatSymbols(dfs); df.applyPattern( "###0.00" ); String s = "9.90" ; System.out.println("non formated d=" + Double.valueOf(s) + " formated d=" +df.format(Double.valueOf(s))); the...

You could do it manual unless using Math.pow do something like this public static long powerN(int number, int power) { int result = number; while(power > 0) { result*=number; power--; } return (long)result; } ...

I'd just suggest printing the double in $f12, not just the float li $v0, 3 mov.d $f12, $f2 syscall ...

java,string,nullpointerexception,type-conversion,double

Do it in this manner private double Doublify(String amountEntered) { try { if(amountEntered!=null){ Double double = Double.parseDouble(amountEntered); }else{ return 0.0; } } catch (NumberFormatException e) { return 0.0; } return double; } ...

ruby,postgresql,csv,double,infinity

First of all, Postgres can probably handle loading CSVs without Ruby's help. As for your question... CSV does not define data types, so whenever you read CSV data into something that expects data types (like Excel or Ruby) the program has to guess. When Excel sees 20150519E000010 it is guessing...

java,double,arithmetic-expressions

You must Typecast the ballsPlayed to double because ballsPlayed is an integer. It returns the integer part of (ballsPlayed % 6) / 10. Thus you got 0 except 0.4. Try this, double o = (double)(( ballsPlayed / 6 ) + ((double) ( ballsPlayed % 6) / 10 )); Here you...

I'm not quire sure I understand the intention of returning a double or and int knowing that's not really possible for a single function to return different data types. What I think I understand from your sample code, is that if a String (For example, "123.0" doesn't matter how many...

You could work with logarithms, and handle the result later as you need. foreach (var word in fileDictionary) { dictionaryTotal.TryGetValue(word.Key, out percent); temp = percent; A += Math.Log10(temp); B += Math.Log10(1 - temp); } You could then operate the resulting logarithms, instead of the resulting numbers....

You're not overriding the Object#equals() method properly -- its signature should be as follows: public boolean equals(Object obj) { The parameter must be of type Object, you would then convert it to Point: @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return...

c,floating-point,double,epsilon

Bounds calculations are convoluted and have holes. See that upper_bound_x[n] == lower_bound_x[n+1]. Then when a compare occurs with (D->values[k][col2] == upper_bound_x[n], it will neither fit in in region n nor region n+1. // Existing code upper_bound_x[0]=min_x+interval_x; //upper bound of the first region in y lower_bound_x[0]=min_x; //lower bound of the first...

java,swing,double,buffer,flicker

My best guess is you have a race condition, where your while-loop is trying to update the BufferedImage, but Swing is also trying to paint it, meaning they are getting dirty updates between them. Also, you might be thrashing the Event Dispatching Thread, which could have it's own, long term...

#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *txt1; char tam[13]; char tam1[13]; char tam2[13]; txt1 = fopen("99.c","r"); if(txt1 == NULL) { printf("No se puede leer el archivo"); return 0; } fgets(tam1,sizeof(tam1), txt1); double c = atof(tam1); printf("%f",c);// change from c } o/p: [email protected]:~/rabi/c$ ./a.out [email protected]:~/rabi/c$ vi...

What you can do is generate a random 64-bit value. This can give you Not-A-Number and +/-Infinity. Random rand = new Random(); double d = Double.longBitsToDouble(rand.nextLong()); Note: Random only produces 2^48 possible long values. You can use SecureRandom to generate all possible 64-bit values but this is much slower. In...

Because of how floats and decimals are represented, the casts could be causing different results. For: double value1 = 0.999939f * 0.987792f you are multiplying two floats and then casting it to a double. The resulting float representation is the one being converted to a double. For: double value2 =...

If you are using the version of Code::Blocks with mingw, see this answer: Conversion specifier of long double in C mingw ... printf does not support the 'long double' type. Some more supporting documentation for it. http://bytes.com/topic/c/answers/135253-printing-long-double-type-via-printf-mingw-g-3-2-3-a If you went straight from float to long double, you may try just...

Try this: NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = decimalMark; nfi.NumberDecimalDigits = decimalDigits; return value.ToString("F" + decimalDigits.ToString(), nfi); ...

The class Double provides a compare method that treats NaNs as being equal. I have tested several of the interesting cases, and in each case it gave the same result as the more indirect String method: public class Test { public static void main(String[] args) { testit(0.0,0.0); testit(0.0, -0.0); testit(Double.NaN,...

If you're limiting you're exponential component to E0 to E99 (for positive exponential) and E0 to E-9 (for negative exponential), you could use a combination of DecimalFormat and Regex to format your results to be 6 characters in length. Something like: public static void main(String[] args) throws Exception { System.out.println(toSciNotation(1000123.456));...

How about using TimeSpan.FromHours method? var ts = TimeSpan.FromHours(5.4898391027272906); Console.WriteLine(ts.Seconds); // 23 Don't use some integer calculations for time intervals. This is exactly what TimeSpan is for. By the way, you code won't even compile. Without any suffix, your 5.4898391027272906 will be double not float and there is no implicit...

Use sed or your favourite text editor to change the Ds to Es, I expect R will happily read the numbers after you do that.

Q is 4241297856 (double)Q has 64-bit IEEE-754 representation 0x41EF99A238000000 In little-endian, the lower 4 bytes of this occupy the same space as (int)Q would. 0x38000000 is 939524096 Handy online converter: http://babbage.cs.qc.edu/courses/cs341/IEEE-754.html...

c#,asp.net,double,nullable,dbnull

Your method could simply be written as public double Difference(object val1, object val2) { double value1; double value2; double.TryParse(val1.ToString(), out value1); double.TryParse(val2.ToString(), out value2); return value1 - value2; } Assuming val1 and val2 are never null(same is true for your code too). Also I made the return type as double....

The simplest solution to the decision tree problem you mention in comments would be to think in terms of the range of doubles that should go to a particular branch of the tree, rather than a single double. However, here is an attempt at the conversion function you asked for:...

java,casting,int,double,rounding

In all the outputs you printed (except the first one which is 0) Speed is smaller than 1 (7.026718463748694E-4, 5.27003884781152E-4, etc...). Notice the negative exponent. Therefore it's no wonder ceil returns 1....

Is my intuition that not all real numbers between the author's two limits would be appropriately held in memory as a double? Yes, you are right. Even the MOST obvious "doubles" cannot be stored correctly. For instance 0.1 is "1/10" - have you ever divided by ten in a...

Your mistake comes from the class declaration. Formal parameter of generic may be T: public class queue<T> { Now you see that T has no method named doubleValue because you haven't constrained it. The following do what you want: import java.util.LinkedList; public class queue<T extends Number> { private final LinkedList<T>...

You are comparing a boolean value to a double. Here is a breakdown of what that line is doing: price == minprice will give a boolean indicating if price is equal to minprice, which you are then asking if it is less than .20*minprice. So you are asking if the...

In regards to your answer to yourself, you don't want to convert an object of type A to type B, operate on it, and then convert it back to type A. Not if you can do anything else. The following does what you want it to do: public double hypotenuse()...

java,android,if-statement,android-activity,double

in this line double cercuils = Double.parseDouble(s.toString()); you parse a String to a Double value. but maybe your String not be a number or it be empty. you can use try catch to if it is number parse it. double cercuils=0; try { cercuils = Double.parseDouble(s.toString()); } catch (NumberFormatException e)...

arrays,matlab,vector,double,complex-numbers

You can temporarily "remove" the minus sign, which causes the complex numbers: vec = [-2.5, 2, -1.5 , 1, -0.5, 0]; sign_vec = sign(vec); test = sign_vec.*((sign_vec.*vec).^1.4623); This results in: test = -3.8186 2.7555 -1.8092 1.0000 -0.3629 0 A generic way of your conversion involves the abs function: >> test...

asp.net,gridview,double,dataformat,boundfield

Thanks for the advice @David W I ended up working it out anyhow. Although I couldn't find any documentation on it, you can give it proper custom formats. Therefore, the following solved my issue; <asp:BoundField DataField="theField" DataFormatString="{0:0.#####}" /> ...

java,split,double,decimal,fractions

You shouldn't work with doubles as you are losing precision and this can lead to serious errors. But in the case of 1.0001 the problem is that: Double.toString(1.0001) == "1.0E-4" Then you try to parse "0E-4" and you get 0 instead of 1. You could do the following if you...

If N is a compile-time constant or if your compiler supports variable length arrays (VLAs), then you could simply do: double (*grid)[N+2] = (double (*)[N+2]) mmap(NULL, ARRAY_SIZE, ... grid[4][5] = 2.0; // setting an element If N is not constant and your compiler doesn't support VLAs, then you need to...

double myArray[x]; Here memory is declared on stack Declared at compile-time, hence faster Accessible only in the scope of the declaring function,( globally if declared global) Will be freed if the declaring function returns generally used when the size of array is known at compile time myArray = malloc(x*sizeof(double)); Here...

binding,javafx,double,javafx-8

You can use Bindings.format instead: sliderValue.textProperty().bind( Bindings.format("Sleep: %.0f", slider.valueProperty()) ); ...

You can use NumberFormat; the #-sign mean that decimals are only shown if they're non-zero. System.out.println("Value in " + new DecimalFormat("0.########").format(m)); ...

c#,string,select,double,stringreader

var point = "POINT (6.5976512883340064 53.011505757047068)"; var indexOfFirstBrace = point.IndexOf('(') + 1; var indexOfLastBrace = point.IndexOf(')'); var coordinates = point.Substring(indexOfFirstBrace, indexOfLastBrace - indexOfFirstBrace).Split(' '); var xCoordinate = coordinates[0]; var yCoordinate = coordinates[1]; ...

Since you are using Double for your arithmetic, why not use the compareTo(Double anotherDouble)? Not sure if this is the source of your trouble, but it could be the == behaving in a way that you did not intend it to and returning false hence, the zero......

No it is not possible, as looking at the documentation double only stores 15 to 16 digits so it will revert to the short format if the number is larger than that. On the other hand ulong is 64 bits and contain a much larger number accurately, and if that...

1,234.56 is not French notation. (Something like 1.234,56 is). Change your locale to Locale.ENGLISH, Locale.US, or similar...

c++,casting,int,double,precision

Almost all widely available hardware uses IETF754 floating point numbers, although C++ does not require it. Assuming IETF754 floating point numbers and a direct mapping of ::std::sqrt to the IETF754 floating point square root operation, you are assured of the following: 16 and 4 can both be represented exactly in...

floating-point,double,ieee-754,floating-point-conversion,significant-digits

First, for this question it is better to use the total significand sizes 24 and 53. The fact that the leading bit is not represented is just an aspect of the encoding. If you are interested only in a vague explanation, one decimal digits contains exactly log2(10) (about 3.32) bits...

From §4 Standard conversions [conv] C++11: Standard conversions are implicit conversions with built-in meaning. Clause 4 enumerates the full set of such conversions. A standard conversion sequence is a sequence of standard conversions in the following order: ... Zero or one conversion from the following set: integral promotions, floating point...