I'm trying to add 0 before each number I'm having but it seems it's not working because I'm using double. I'm using double so I can input numbers such as 1.5 (hours) and translate it to seconds, minutes, and hours (Output should be 0 seconds, 30 minutes, and 1 hour and 01:30:00). I'm having no problems with the first output but I can't seem to do the second output (The desired 01:30:00 only displays 1:30:0). What I did first is I tried to convert the double variable to int32 then to string but it seems to not work. Here's the code:
If SecondsRemainder >= 0 And SecondsRemainder < 10 Then
SecondsRemainder = Convert.ToInt32(SecondsRemainder)
SecondsRemainder.ToString.PadLeft(2, "0")
End If
This line of code:
SecondsRemainder.ToString.PadLeft(2, "0")
Doesn't seem to do anything, am I missing something out? Or is there any other way I can do? Looking forward to your answers!
Let's look at this line piece by piece, and see what it actually does:
SecondsRemainder.ToString.PadLeft(2, "0")
We start with the SecondsRemainder variable. This variable is still a Double, in spite of the earlier code using Convert.ToInt32(). Remember, at it's core VB.Net is a statically typed language! When you declare a variable with a specific type, the variable's type can never change.
We now call the .ToString() method for this variable. Note this really is a method, not a property. Good practice for .Net is to include the parentheses when calling methods, even though they aren't strictly required with VB. If I reviewed that code, I'd ask you to change it to show the parentheses. Remember, we're also getting the Double version of this method, rather than the Integer version. You're probably okay here, but the double version can do weird things for formatting you might not expect from an integer.
Finally, we take the string result from the previous method and call PadLeft(). This mostly does what you expect. However, there is no overload that takes a number and a string. Frankly, I'm surprised this even compiles, and it tells me you likely don't have Option Strict set correctly. No self-respecting programmer runs with Option Strict Off anymore. The correct way to call this function is like this:
.PadLeft(2, "0"c)
Where the c suffix gives you a character value rather than a string value.
And that's it. We're done. This function returns a result. It does not modify the calling variable. So we've done all this work, and discard the result without actually changing anything.
What I would do to fix your issue is declare a new string variable to receive the result. Then I would use this code to assign to it:
'Create a string variable to hold your string result
Dim RemainderString As String = ""
'Use double literals to compare with double variables!
If SecondsRemainder >= 0.0 And SecondsRemainder < 10.0 Then
'Use a format string directly from the initial double value to create your string result
' and don't forget to assign it to a variable
RemainerString = SecondsRemainder.ToString("00")
End If
You may also want to use Math.Round() first, as this code would still create "01" from a 1.9999 input.
Finally, I'm wondering how you're using this SecondsRemainder value. VB.Net has a whole set of methods for building date and time strings and values, and a variable name like SecondsRemainder sounds like you're doing something the hard way that could be much MUCH easier.
I'm wondering if the answer is that you are approaching the problem incorrectly. You seem to be computing some time value. If so use TimeSpan.
Dim ts As TimeSpan = TimeSpan.FromHours(1.51#)
' ts.TotalSeconds
' ts.Seconds
Dim s As String = ts.ToString("hh\:mm\:ss")
Related
I had a strange error in a VB6 app this morning and it all stems from the fact that IsNumeric is not working as I expected. Can someone shed some light on why? To me this seems like a bug.
This code displays 4.15877E+62 in a message box:
Dim strMessage As String
strMessage = "0415877D57"
If IsNumeric(strMessage) Then
MsgBox CDbl(strMessage)
Else
MsgBox "not numeric"
End If
I am guessing that the runtime engine is incorrectly thinking that the D is in fact an E?
I think this is a bug though as the exact same code in VB.NET outputs not numeric
Is this a known issue with IsNumeric?
If you check the VB6 docs:
Note Floating-point values can be expressed as mmmEeee or mmmDeee, in which mmm is the mantissa and eee is the exponent (a power of 10). The highest positive value of a Single data type is 3.402823E+38, or 3.4 times 10 to the 38th power; the highest positive value of a Double data type is 1.79769313486232D+308, or about 1.8 times 10 to the 308th power. Using D to separate the mantissa and exponent in a numeric literal causes the value to be treated as a Double data type. Likewise, using E in the same fashion treats the value as a Single data type.
I've been using my own IsNumber function for a long time exactly because of this situation. IsNumeric can also return true for certain money symbols, like this: IsNumeric("$34.20").
My IsNumber function looks like this:
Public Function IsNumber(ByVal Data As String) As Boolean
If Data = "" Then
IsNumber = False
Exit Function
End If
IsNumber = IsNumeric(Data & "e0")
End Function
The idea here is... if there is already an e or d in the data, adding another will cause the data to NOT be numeric using the IsNumeric check. You can easily change this function to only allow for integers by replacing "e0" with ".0e0". Want just positive integers? then use this: IsNumeric("-" & Data & ".0e0")
The only downside of this method is that an empty string normally is not numeric, but when you append "e0" to it, it becomes numeric so you need to add a check for that, like I did in my code.
I suggest making a custom validator. Do you want to allow 0-9 only? What about negatives? Commas? I never cared for Microsoft's implementation, but I understand it.
I have a situation where I want have many temperatures placed in column vectors, for example T101, T102, … and I would like to access these using a string cat command and place them in another vector. I created a simplified example to show what I am trying to achieve.
clc
clear all
T102 = [5; 8; 20; 21];
P102 = [T102;1]
P102 = [strcat('T','102');1]
However, I am receiving an error for the second time I define P102 because it has now become the string 'T102' and I want it to become the variable T102 and not the string.
I am not sure what you are trying to do and if it’s the right way.
But to answer your question you should use eval:
P102 = [eval(strcat('T','102'));1];
I have the bizarre error in python 3.4 where multiplication does not work!
This is my code:
timerlenth = input('Please enter the amount of minute: ')
int(timerlenth)
timersec = (timerlenth*60)
print (timersec)
Here is a photo of the result:
I am practically clueless on trying to solve the problem!
The input function returns a string. Therefore the variable timerlenth stores a string. Next line, int(timerlenth) converts this variable to integer, but does nothing with the result, leaving the timerlenth as the same string it used to be. Python has this functionality where [string]*x will repeat the string x times and that's what you see in the output.
To get actual multiplication, you'll have to store the value of int(timerlenth) to a variable, preferably a new one (good programming practice) and use the new value with multiplication operation.
timerlenth is a string, so the * operator just concatinates it 60 times instead of multiplying it. This caused by your misuse of int - it doesn't change the passed argument, it returns an integer value for it, which you then lose by not assigning it anywhere. Just reassign it to timerlenth and you should be fine:
timerlenth = int(timerlenth)
Today I've finally decided to make an account, in hope for some aid in an issue I've spent the last few hours hunting. (I've spent the past couple hours hunting down a response, from Google to here to Unity Answers. Here's everything that I've found so far, which doesn't work.)
What I'm looking for, is to change a string of purely words/letters into an integer. Therefore "Hello World", would be translated into a string of numbers accordingly. This may be surprising, but this is a lot harder than it sounds. I've found a way to do essentially everything but, thus far.
Presumably the best way would be to get the ASCII value of each letter in the string, and put them all together into a single integer. (No sequences or need to separate them, but one single number.) I have no idea where to get started or how to do that, however. Really anything that you think would work, preferably as short-hand and un-bothersome as possible.
To be as clear as possible, I need to take the letter-only variable "example" and transmorph it to be a integer/only a sequence of numbers.
If you're just trying to convert an arbitrary string into a random seed, then why not try randomSeed.GetHashCode()? That will return an int value suitable for setting the seed, which would produce the same number each time the same string is entered.
You can iterate over all characters, get their charCode and chain them together. The first method splits the string into single chars and uses Array.reduce:
var str = 'qwertzuiop';
var num = parseInt(str.split('').reduce(function(a, b) {return a + b.charCodeAt(0);}, '');
The second calls Array.forEach on the string, because it has numerical indices and a length property.
var num = ''; [].forEach.call(str, function(c) {num += c.charCodeAt(0);});
num = parseInt(num);
In stoneaged browsers you have to use for-loops instead.
I would like to define a function which returns the string "NaN" or sprintf("%g",val) depending on whether val is a string or a numeric value. Initially I was trying to test if val was defined (using the gnuplot "exists" function) but it seems that I cannot pass any undefined variable to a function (an error is issued before the function is evaluated). Therefore: is there a way to test inside a function whether the argument is a string or numeric?
I search for a function isstring which I can use somehow like
myfunc(val)=(isstring(val)?"NaN":sprintf("%g",val))
The goal is to output the values of variables without risking errors in case they are undefined. However I need it as a function if I want a compact code for many variables.
Gnuplot doesn't really have the introspection abilities that many other languages have. In fact, it treats strings and numbers (at least integers) very similarly:
print "1"+2 #prints 3
a=1
print "foo".a #prints foo1
I'm not exactly sure how this is implemented internally. However, what you're asking is very tricky to get to work.
Actually, I think your first attempt (checking if a variable exists) is more sensible as type-checking in gnuplot is impossible*. You can pass the variable name to the function as a string, but the problem is that you don't seem to have a handle on the value. All seems lost -- But wait, gnuplot has an eval statement which when given a string will evaluate it. This seems great! Unfortunately, it's a statement, not a function (so it can't be used in a function -- argv!). The best solution I can come up with is to write a function which returns an expression that can be evaluated using eval. Here goes:
def exists_func(result,var)=sprintf("%s=exists('%s')?sprintf('%g',var):'NaN'",result,var,var)
Now when you want to use it, you just prefix it with eval
a=3
eval exists_func("my_true_result","a")
print my_true_result #3
eval exists_func("my_false_result","b")
print my_false_result #NaN
This goes against the grain a little bit. In most programming languages, you'd probably want to do something like this:
my_true_result=exists_func(a)
But alas, I can't figure out how to make that form work.
Of course, the same thing goes here that always goes with eval. Don't use this function with untrusted strings.
*I don't actually know that it's impossible, but I've never been able to get it to work
EDIT
In response to your comment above on the question, I think a function like this would be a little more intuitive:
def fmt(x)=(x==x)?sprintf("%g",x):"NaN"
With this function, your "sentinal/default" value should be NaN instead of "undefined", but it doesn't seem like this should make too much of a difference...(Really, if you're willing to live with "nan" instead of "NaN" you don't need this function at all -- sprintf will do just fine. (Note that this works because according to IEEE, NaN doesn't equal anything (even itself)).
You helped me a lot these days with gnuplot. I want to give you something back because I have found a solution to check if a variable is numeric or not. This helps to decide which operators can be used on it (e.g. == for numbers, eq for strings).
The solution is not very simple, but it works. It redirects gnuplot's print command to a temp file, writes the variable to the file with print myvar and evaluates the file's first line with system("perl -e '<isnumeric(line#1 in temp file)?>' ") (<> is pseudo-code). Let me know if there's room for imrpovements and let me hear your suggestions!
Example: myvar is a float. Any integer (1 or "1") or string value ("*") works too!
myvar = -2.555
# create temporary file for checking if variables are numeric
Int_tmpfle = "tmp_isnumeric_check"
# redirect print output into temp file (existing file is overwritten)
set print Int_tmpfle
# save variable's value to file
print myvar
# check if file is numeric with Perl's 'looks_like_number' function
isnumeric = system("perl -e 'use Scalar::Util qw(looks_like_number); \
open(FLE,".Int_tmpfle."); $line = < FLE >; \
if (looks_like_number($line) > 0) {print qq(y)} ' ")
# reset print output to < STDOUT> (terminal)
set print "-"
# make sure to use "," when printing string and numeric values
if (isnumeric eq "y") {print myvar," is numeric."} else {print myvar," is not numeric."}