Consequences of Implementing To_Int and To_Str in Ruby

`to_s` isn't converting an integer to a string

When you call puts on an array, it outputs each element of the array separately with a newline after each element. To confirm that your to_s methods are converting the number to a string, try using print instead of puts.

As for the nil that's output, that is the return value of your function. Unless there is an explicit return, the return value of a function will be the evaluation of the last line, which in your case is: puts number. The return value of puts number is nil; printing the value of number is a side effect, not the return value.

I'm curious as to why the output was indeed an array in your first lines of code (not within the function):

$  num = 233
$ number = num.to_s.split(//)
$ puts number
=> ['2', '3', '3']

I suspect that you actually saw that output after the num.to_s.split(//) line, not the puts number line.

JavaScript: why are some functions not methods?

In general, Javascript was designed in a hurry, so questioning each individual design decision isn't always a productive use of your time.

Having said that, for parseInt in particular, the reason is simple to explain: it accepts pretty much any arbitrary type, like:

parseInt(undefined)  // NaN

Since you cannot implement undefined.parseInt(), the only way to do it is to implement it as a static function.

As of ECMAScript 2015, parseInt has been mirrored in Number.parseInt, where it arguably makes more sense than on window. For backwards compatibility window.parseInt continues to exist though.

When should I use double or single quotes in JavaScript?

The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string.

Using the other type of quote as a literal:

alert('Say "Hello"');
alert("Say 'Hello'");

This can get complicated:

alert("It's \"game\" time.");
alert('It\'s "game" time.');

Another option, new in ECMAScript 6, is template literals which use the backtick character:

alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);

Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.

Note that JSON is formally specified to use double quotes, which may be worth considering depending on system requirements.

string.Join on a List int or other type

The best way is to upgrade to .NET 4.0 where there is an overload that does what you want:

  • String.Join<T>(String, IEnumerable<T>)

If you can't upgrade, you can achieve the same effect using Select and ToArray.

    return string.Join(",", a.Select(x => x.ToString()).ToArray());

Why not use Double or Float to represent currency?

Because floats and doubles cannot accurately represent the base 10 multiples that we use for money. This issue isn't just for Java, it's for any programming language that uses base 2 floating-point types.

In base 10, you can write 10.25 as 1025 * 10-2 (an integer times a power of 10). IEEE-754 floating-point numbers are different, but a very simple way to think about them is to multiply by a power of two instead. For instance, you could be looking at 164 * 2-4 (an integer times a power of two), which is also equal to 10.25. That's not how the numbers are represented in memory, but the math implications are the same.

Even in base 10, this notation cannot accurately represent most simple fractions. For instance, you can't represent 1/3: the decimal representation is repeating (0.3333...), so there is no finite integer that you can multiply by a power of 10 to get 1/3. You could settle on a long sequence of 3's and a small exponent, like 333333333 * 10-10, but it is not accurate: if you multiply that by 3, you won't get 1.

However, for the purpose of counting money, at least for countries whose money is valued within an order of magnitude of the US dollar, usually all you need is to be able to store multiples of 10-2, so it doesn't really matter that 1/3 can't be represented.

The problem with floats and doubles is that the vast majority of money-like numbers don't have an exact representation as an integer times a power of 2. In fact, the only multiples of 0.01 between 0 and 1 (which are significant when dealing with money because they're integer cents) that can be represented exactly as an IEEE-754 binary floating-point number are 0, 0.25, 0.5, 0.75 and 1. All the others are off by a small amount. As an analogy to the 0.333333 example, if you take the floating-point value for 0.01 and you multiply it by 10, you won't get 0.1. Instead you will get something like 0.099999999786...

Representing money as a double or float will probably look good at first as the software rounds off the tiny errors, but as you perform more additions, subtractions, multiplications and divisions on inexact numbers, errors will compound and you'll end up with values that are visibly not accurate. This makes floats and doubles inadequate for dealing with money, where perfect accuracy for multiples of base 10 powers is required.

A solution that works in just about any language is to use integers instead, and count cents. For instance, 1025 would be $10.25. Several languages also have built-in types to deal with money. Among others, Java has the BigDecimal class, and Rust has the rust_decimal crate, and C# has the decimal type.

How expensive is a GUID cast and comparison vs a string comparison

I used this code:

object victim = Guid.Empty;
Guid target = Guid.NewGuid();

Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 10000000; i++){
bool equal = ((Guid) victim) == target;
}
Console.WriteLine("Direct cast : {0}", sw.Elapsed);

sw.Reset(); sw.Start();
for (int i = 0; i < 10000000; i++)
{
bool equal = Guid.Equals(victim, target);
}
Console.WriteLine("Guid.Equals : {0}", sw.Elapsed);

sw.Reset(); sw.Start();
string a = victim.ToString(); // as suggested by Mikael
string b = target.ToString();
for (int i = 0; i < 10000000; i++)
{
bool equal = String.Equals(a, b, StringComparison.OrdinalIgnoreCase);
}
Console.WriteLine("String.Equals : {0}", sw.Elapsed);

Console.ReadLine();

And got this result for different values (best scenario):

object victim = Guid.Empty;
Guid target = Guid.NewGuid();
// Direct cast : 00:00:00.1164198
// Guid.Equals : 00:00:02.1268147
// String.Equals : 00:00:00.4129527 // oh my!

And this result for same value (worse scenario)

object victim = Guid.Empty;
Guid target = Guid.Empty;
// Direct cast : 00:00:00.2793173
// Guid.Equals : 00:00:03.5625948
// String.Equals : 00:00:01.7564302

How do I convert a check to words that includes the decimal position as well

Try this:

public class CheckToWord {
public static void main(String[] args) { //main method
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the check amount:"); //prompt user to enter check amount

double number = scanner.nextDouble();
String[] parsed = parse(Double.toString(number));
int main = Integer.parseInt(parsed[0]);
int change = Integer.parseInt(parsed[1]);

if (main == 0 && change == 0) {
System.out.print("Zero");
} else {
String mwm = moneyWord(main);
String mwc = moneyWord(change);
System.out.println("" + mwm + " and " + mwc + " cents");
}
}

private static String[] parse(String number) {
String[] split = number.contains(".") ? number.split(Pattern.quote(".")) : new String[]{number, "00"};
String main = split[0];
String change = split[1].length() >= 2 ? split[1].substring(0, 2) :
split[1].length() == 1 ? split[1] + "0" : "00";
return new String[]{main, change};
}

private static String moneyWord(int number) {
if(number > 1000) {
throw new IllegalArgumentException("Number value should be less than 1000");
}

String words = ""; // variable to hold string representation of number
String onesArray[] = {"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen"};
String tensArray[] = {"zero", "ten", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety"};

if (number < 0) { // convert the number to a string
String numberStr = "" + number;
numberStr = numberStr.substring(1); // remove minus before the number
return "minus " + moneyWord((int) Double.parseDouble(numberStr)); // add minus before the number and convert the rest of number
}

if ((number / 1000) > 0) { // check if number is divisible by 1 thousand
words += moneyWord(number / 1000) + " thousand ";
number %= 1000;
}

if ((number / 100) > 0) { // check if number is divisible by a hundred
words += moneyWord(number / 100) + " hundred ";
number %= 100;
}

if (number < 20) { // check if number is within the teens
words += onesArray[number]; // get the appropriate value from ones array
} else {
words += tensArray[number / 10]; // get the appropriate value from tens array
if ((number % 10) > 0) {
words += "-" + onesArray[number % 10];
}
}
return words;
}
}

Example output:

Please enter the check amount:
10.25
ten and twenty-five cents

How to perform an integer division, and separately get the remainder, in JavaScript?

For some number y and some divisor x compute the quotient (quotient)[1] and remainder (remainder) as:

const quotient = Math.floor(y/x);
const remainder = y % x;

Example:

const quotient = Math.floor(13/3); // => 4 => the times 3 fits into 13  
const remainder = 13 % 3; // => 1

[1] The integer number resulting from the division of one number by another



Related Topics



Leave a reply



Submit