There seems to be some inconsistency with the way tryParse is used in Dart or I'm going about it a silly way, likely the latter.
When we use the int.tryParse statement, if we pass it 10.0 as a double, we would expect to get 10 which we do.
print(int.tryParse(10.0.toString())); ==> 10
If we pass it 10.0 as a string, it will return null.
print(int.tryParse('10.0')); ==> null
I find this a bit strange as I would have thought 10.0.toString() is equivalent to '10.0'.
Does anyone have an explanation?
The difference is between web compiler and native code.
When Dart is compiled to the web (to JavaScript), all numbers are JavaScript numbers, which effectively means doubles.
That means that the integer 10 and the double 10.0 is the same object. There is only on "10" value in JavaScript.
So, when you do toString on that value, it has to choose, and it chooses "10" over "10.0".
When run natively, the double 10.0 and the integer 10 are two different objects, and their toStrings are "10.0" and "10" respectively.
The int.tryParse function does not accept "10.0" as input, which is why it returns null.
So, when testing on the web (including dartpad.dev), int.tryParse(10.0.toString()) succeeds because the toString is "10", and when testing natively the same code gives null because the toString is "10.0".
10.0.toString() returns '10', not '10.0'. That's why you have different results. Here is just the same question. So, as I understand it, we have:
dart 10.0 parses as int on js target (and there is not such a big difference between int and double on js target, as said on the link);
dart 10.0 parses as double on dart VM, but toString returns the shortest possible text representation of that number, that is 10.
This seems to be a compiler behaviour. I can't find someone reporting this issue. Maybe when you have zeroes after the comma, the toString method will round it. If all zeroes after comma, then it will convert to int.
Related
I have a Flutter project, in SharedPrefs, I'm storing a double id, from a Third-part API. (so I can only get it as a double)
The id from prefs is 43449716574226770.0
I have to parse this double to a String, I'm doing it like this:
String idString = id.toStringAsFixed(0)
What I'm getting is somehow: 43449716574226768 but I'd like it to be just 43449716574226770
I have tried .toInt().toString() too, with the same results.
The weirdest part is that it sometimes works, with other ids.
This number as long would be in a 6-byte range?
As double this with an exponent part, this might mean that the previous double (bit wise) would have a difference more than 1. Also see java Math.ulp.
This implies that using a double instead of a long maps some double IDs to the same "long" ID.
I am not sure this is the problem here, but it would explain a deviation of 2.
Can you please try this
double x=43449716574226770.0;
print(x.toString());
Make it id.round().toString(), it will work.
Trying to understand how "%s%s" %(a,a) is working in below code I have only seen it inside print function thus far.Could anyone please explain how it is working inside int()?
a=input()
b=int("%s%s" %(a,a))
this "%s" format has been borrowed from C printf format, but is much more interesting because it doesn't belong to print statement. Note that it involves just one argument passed to print (or to any function BTW):
print("%s%s" % (a,a))
and not (like C) a variable number of arguments passed to some functions that accept & understand them:
printf("%s%s,a,a);
It's a standalone way of creating a string from a string template & its arguments (which for instance solves the tedious issue of: "I want a logger with formatting capabilities" which can be achieved with great effort in C or C++, using variable arguments + vsprintf or C++11 variadic recursive templates).
Note that this format style is now considered legacy. Now you'd better use format, where the placeholders are wrapped in {}.
One of the direct advantages here is that since the argument is repeated you just have to do:
int("{0}{0}".format(a))
(it references twice the sole argument in position 0)
Both legacy and format syntaxes are detailed with examples on https://pyformat.info/
or since python 3.6 you can use fstrings:
>>> a = 12
>>> int(f"{a}{a}")
1212
% is in a way just syntactic sugar for a function that accepts a string and a *args (a format and the parameters for formatting) and returns a string which is the format string with the embedded parameters. So, you can use it any place that a string is acceptable.
BTW, % is a bit obsolete, and "{}{}".format(a,a) is the more 'modern' approach here, and is more obviously a string method that returns another string.
Very simple.
I want to be able to convert scientific notation to a double in Visual Basic 6.
For example :
5.97427068015303E-10
I have tried :
results.Text = CDbl("5.97427068015303E-10")
results.Text = CDbl(5.97427068015303E-10)
Not working...
The value 5.97427068015303E-10 already is a Double value. I don't think the word convert means what you think it does. Conversion functions certainly won't accomplish what you appear to be after.
I suspect what you are trying to express is that you want to format such tiny values as text in simple decimal notation. If so you might try something like:
Text1.Text = Format$(5.97427068015303E-10, "0.0########################")
I've contered a Python 2 code to Python 3.
In doing so, I've changed
print 'String: ' + somestring
into
print(b'String: '+somestring)
because I was getting the following error:
Can't convert 'bytes' object to str implicitly
But then now I can't implement string attributes such as strip(), because they are no longer treated as strings...
global name 'strip' is not defined
for
if strip(somestring)=="":
How should I solve this dilemma between switching string to bytes and being able to use string attributes? Is there a workaround?
Please help me out and thank you in advance..
There are two issues here, one of which is the actual issue, the other is confusing you, but not an actual issue. Firstly:
Your string is a bytes object, ie a string of 8-bit bytes. Python 3 handles this differently from text, which is Unicode. Where do you get the string from? Since you want to treat it as text, you should probably convert it to a str-object, which is used to handle text. This is typically done with the .decode() function, ie:
somestring.decode('UTF-8')
Although calling str() also works:
str(somestring, 'UTF8')
(Note that your decoding might be something else than UTF8)
However, this is not your actual question. Your actual question is how to strip a bytes string. And the asnwer is that you do that the same way as you string a text-string:
somestring.strip()
There is no strip() builtin in either Python 2 or Python 3. There is a strip-function in the string module in Python 2:
from string import strip
But it hasn't been good practice to use that since strings got a strip() method, which is like ten years or so now. So in Python 3 it is gone.
>>> b'foo '.strip()
b'foo'
Works just fine.
If what you're dealing with is text, though, you probably should just have an actual str object, not a bytes object.
I believe you can use the "str" function to cast it to a string
print str(somestring).strip()
or maybe
print str(somestring, "utf-8").strip()
However, if the object is already a string, you don't get a new one. So if you're not sure whether an object is a string and need it to be and call str(obj), you won't create another if it's already a string.
x='123'
id(x)
2075707536496
y=str(x)
id(y)
2075707536496
I'm using the NVelocity Templating engine to produce a fixed-length field output - you know the kind of thing:
Field Start Pos Field Length Notes
---------- --------- ------------ ---------
Supplier 1 7 Leading Zeros
GRN 8 9 -
...
e.g.
>0001234 123A<
The problem is I'm trying to call String.PadRight() with the overload to specify the leading zero, and NVelocity is having none of it..
This works:
$Document.SupplierCode.PadRight(7)
But this doesn't:
$Document.SupplierCode.PadRight(7,"0")
I've tried:
Single Quotes ('0')
Double Single-Quotes (''0'')
Double Quotes ("0")
Double Double-Quotes (""0"")
Escaping the quotes for all of the above (\"0\")
No Quotes!
All I've found to work from is the NVelocity Homepage, and the Velocity Templating Language Reference page, niether are pointing me at a solution.
Sorry I'm unable to supply or point you somewhere where you can test out your ideas for yourself, but any suggestions you may have will be most welcome!
Thanks for your help ;o)
I'm coping with the same problem at the moment, as far as I understand it is due to the fact that PadLeft and PadRight functions of String class receive the second parameter, the leading "0", as a char, not as a string.
NVelocity allows you to specify the parameter as a string using '0', but in this way internally it generate a cast exception (or something similar), because the parameter is expected as char.
I haven't found yet (I'm just using NVelocity since 1 hour!) a way to specify the parameter as char, at the moment I have just a dirty solution such as applying a Replace(" ", "0") after the PadLeft / PadRight, so the template becomes
$Document.SupplierCode.PadRight(7).Replace(' ', '0')
One solution that a colleague has come up with is to create another property in the Document object that returns the formatted String:
E.g.
Public ReadOnly Property SupplierCodeFormatted() As String
Get
Return Supplier.Code.PadLeft(7, "0")
End Get
End Property