Wednesday, 16 December 2015

Kata Day 21: Formatting decimal places


Problem Description: Each number should be formatted that only the first two decimal places are returned. You don't need to check whether the input is a valid number because only valid numbers are used in the tests.

Don't round the numbers! Just cut them after two decimal places!

Right examples:  
32.8493 is 32.84  
14.3286 is 14.32

Incorrect examples (e.g. if you round the numbers):  
32.8493 is 32.85  
14.3286 is 14.33

Level:7kyu

Link to kata: Formatting decimal places

This was an easy kata. The only catch was that we don't have to round up a decimal but rather we have to cut the given number to 2 decimal places. I first converted the given number to a string and then found the index of decimal(.) in the string. The index was assigned to a variable 'n'. We then divided the string in two parts. One part was from starting of string to just before the decimal point and the other part from the decimal point to next two places after it. We then merge these two substrings and parse the string to a float. 

Please keep in mind that the online judge fails the solution if we return the string as an answer without parsing it to a float. 

Here is a link to the code: Kata day 21

Please mention your suggestions or your doubts in the comment below.


Happy coding. :)

No comments:

Post a Comment