Converting String 2½ (two and a half) into 2.5
Unicode only supports a small number of vulgar fractions so a simple lookup table will do the trick:
# You might want to double check this mapping
vulgar_to_float = {
"\u00BC" => 1.0 / 4.0,
"\u00BD" => 1.0 / 2.0,
"\u00BE" => 3.0 / 4.0,
"\u2150" => 1.0 / 7.0,
"\u2151" => 1.0 / 9.0,
"\u2152" => 1.0 /10.0,
"\u2153" => 1.0 / 3.0,
"\u2154" => 2.0 / 3.0,
"\u2155" => 1.0 / 5.0,
"\u2156" => 2.0 / 5.0,
"\u2157" => 3.0 / 5.0,
"\u2158" => 4.0 / 5.0,
"\u2159" => 1.0 / 6.0,
"\u215A" => 5.0 / 6.0,
"\u215B" => 1.0 / 8.0,
"\u215C" => 3.0 / 8.0,
"\u215D" => 5.0 / 8.0,
"\u215E" => 7.0 / 8.0,
"\u2189" => 0.0 / 3.0,
}
Then, a little bit of regex wrangling to pull your "number" apart:
s = "2½"
_, int_part, vulgar_part = *s.match(/(\d+)?(\D+)?/)
And finally, put them together taking care to properly deal with possible nil
s from the regex:
float_version = int_part.to_i + vulgar_to_float[vulgar_part].to_f
Remember that nil.to_i
is 0
and nil.to_f
is 0.0
.
Convert object into float (6½ to 6.5)
Use str.replace to replace '½' with '.5' & then use astype(float)
to convert the values to float
. Code below.
df['Total'] = df['Total'].str.replace('½','.5').astype(float)
Input
Total
0 6
1 5
2 5
3 5½
4 5½
5 6½
6 6½
Output
Total
0 6.0
1 5.0
2 5.0
3 5.5
4 5.5
5 6.5
6 6.5
Convert int to string?
string myString = myInt.ToString();
ValueError: invalid literal for int () with base 10
Answer:
Your traceback is telling you that int()
takes integers, you are trying to give a decimal, so you need to use float()
:
a = float(a)
This should work as expected:
>>> int(input("Type a number: "))
Type a number: 0.3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0.3'
>>> float(input("Type a number: "))
Type a number: 0.3
0.3
Computers store numbers in a variety of different ways. Python has two main ones. Integers, which store whole numbers (ℤ), and floating point numbers, which store real numbers (ℝ). You need to use the right one based on what you require.
(As a note, Python is pretty good at abstracting this away from you, most other language also have double precision floating point numbers, for instance, but you don't need to worry about that. Since 3.0, Python will also automatically convert integers to floats if you divide them, so it's actually very easy to work with.)
Previous guess at answer before we had the traceback:
Your problem is that whatever you are typing is can't be converted into a number. This could be caused by a lot of things, for example:
>>> int(input("Type a number: "))
Type a number: -1
-1
>>> int(input("Type a number: "))
Type a number: - 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '- 1'
Adding a space between the -
and 1
will cause the string not to be parsed correctly into a number. This is, of course, just an example, and you will have to tell us what input you are giving for us to be able to say for sure what the issue is.
Advice on code style:
y = [int(a)**(-2),int(a)**(-1.75),int(a)**(-1.5),int(a)**(-1.25),
int(a)**(-1),int(a)**(-0.75),int(a)**(-0.5),int(a)**(-0.25),
int(a)**(0),int(a)**(0.25),int(a)**(0.5),int(a)**(0.75),
int(a)**1,int(a)**(1.25),int(a)**(1.5),int(a)**(1.75), int(a)**(2)]
This is an example of a really bad coding habit. Where you are copying something again and again something is wrong. Firstly, you use int(a)
a ton of times, wherever you do this, you should instead assign the value to a variable, and use that instead, avoiding typing (and forcing the computer to calculate) the value again and again:
a = int(a)
In this example I assign the value back to a
, overwriting the old value with the new one we want to use.
y = [a**i for i in x]
This code produces the same result as the monster above, without the masses of writing out the same thing again and again. It's a simple list comprehension. This also means that if you edit x
, you don't need to do anything to y
, it will naturally update to suit.
Also note that PEP-8, the Python style guide, suggests strongly that you don't leave spaces between an identifier and the brackets when making a function call.
Code Golf: Number to Words
Lisp, using only standard functions:
(format nil "~r" 1234) ==> "one thousand two hundred thirty-four"
Bonus:
(format nil "~@r" 1234) ==> "MCCXXXIV"
Split a string into 2 in Python
Python 2:
firstpart, secondpart = string[:len(string)/2], string[len(string)/2:]
Python 3:
firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]
How to round a Double to the nearest Int in swift?
There is a round
available in the Foundation
library (it's actually in Darwin
, but Foundation
imports Darwin
and most of the time you'll want to use Foundation
instead of using Darwin
directly).
import Foundation
users = round(users)
Running your code in a playground and then calling:
print(round(users))
Outputs:
15.0
round()
always rounds up when the decimal place is >= .5
and down when it's < .5
(standard rounding). You can use floor()
to force rounding down, and ceil()
to force rounding up.
If you need to round to a specific place, then you multiply by pow(10.0, number of places)
, round
, and then divide by pow(10, number of places)
:
Round to 2 decimal places:
let numberOfPlaces = 2.0
let multiplier = pow(10.0, numberOfPlaces)
let num = 10.12345
let rounded = round(num * multiplier) / multiplier
print(rounded)
Outputs:
10.12
Note: Due to the way floating point math works, rounded
may not always be perfectly accurate. It's best to think of it more of an approximation of rounding. If you're doing this for display purposes, it's better to use string formatting to format the number rather than using math to round it.
Convert string to decimal ignore point
You can probably fix it by changing your default culture, or by forcing the use of a specific culture in the conversion calls (a).
Our wonderful, yet somehow slightly disturbing European cousins have gotten the decimal point and comma mixed up at some point in the past, so that thirty-five-thousand-and-seven-point-two-five is written as:
35.007,25
So what's almost certainly happening is that your culture settings are throwing away the thousands separator (regardless of where they are) so that "2.5" is 25. This means that a number like two-and-half-thousand (2,500
) would almost certainly become two-and-a-half.
(a): In fact, you probably shouldn't force a specific culture in the conversion call, since the whole point of cultures is to adapt to people's needs. The Europeans thinks little enough of US bods already without giving them more reasons :-) What you're seeing is exactly what's supposed to be happening.
If you need a specific culture, configure your machine that way, and let your code use the default.
Convert array of strings into a string in Java
Java 8+
Use String.join()
:
String str = String.join(",", arr);
Note that arr
can also be any Iterable
(such as a list), not just an array.
If you have a Stream
, you can use the joining collector:
Stream.of("a", "b", "c")
.collect(Collectors.joining(","))
Legacy (Java 7 and earlier)
StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
}
String str = builder.toString();
Alternatively, if you just want a "debug-style" dump of an array:
String str = Arrays.toString(arr);
Note that if you're really legacy (Java 1.4 and earlier) you'll need to replace StringBuilder
there with StringBuffer
.
Android
Use TextUtils.join()
:
String str = TextUtils.join(",", arr);
General notes
You can modify all the above examples depending on what characters, if any, you want in between strings.
DON'T use a string and just append to it with += in a loop like some of the answers show here. This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array. For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.
Related Topics
What Are Some Good Role Authorization Solutions Used with Authlogic
Is There a Method to Limit/Clamp a Number
How to Convert Activerecord Table Name to Model Class Name
How to Read a Gzip File Line by Line
Rake Db:Migrate Is Being Aborted Due to Rake Version Difference
Configuration in Allure to Cucumber in Ruby
Positive Lookahead Doesn't Stop at First Occurrence
How to Add a Custom Log Level to Logger in Ruby
Simple Conversion of String to Utf-8 in Ruby 1.8
Authlogic Perishable_Token Resets on Every Request
Ruby -V Dyld: Library Not Loaded: /Usr/Local/Lib/Libgmp.10.Dylib
Is It Necessary to Close Stringio in Ruby
Split Seeds.Rb into Multiple Sections
Exec': String Contains Null Byte (Argumenterror)
Custom Filtering of Parameters in Rails 3 Using Config.Filter_Parameters
Multi Level Block Method Is Generating Issue
Rails Helper - How to Get a Helper to Give Me a '<Br/>' (Or Other Markup)