C
C#2w ago
SkullereQ

Basic C# question

using System; namespace DecimalPart { internal class Program { static void Main(string[] args) { string number = Console.ReadLine(); double number2 = Convert.ToDouble(number); double number3 = Math.Floor(number2); double number4 = Math.Round(number2-number3,6); Console.WriteLine($"Decimal part = {number4}"); } } this is my input: 13.62001 this is output that i should get: Decimal part = 0.620010 how do i get 6 digits behind even when there is no 6 digits for example 26.389 and i want to get 0.389000? This is what I'm getting: Decimal part = 0.62001
13 Replies
mg
mg2w ago
Standard numeric format strings - .NET
In this article, learn to use standard numeric format strings to format common numeric types into text representations in .NET.
mg
mg2w ago
{number4} is implicitly telling the program to convert number4 to a string, and there are many ways to do that the default is what you're getting, so you have to specify that you want 6 digits after the decimal point
SkullereQ
SkullereQOP2w ago
i did that Math.Round(number2-number3,6); that six behind
mg
mg2w ago
oops, wrong section
mg
mg2w ago
Standard numeric format strings - .NET
In this article, learn to use standard numeric format strings to format common numeric types into text representations in .NET.
mg
mg2w ago
but, mathematically, is there a difference between 13.62001 and 13.620010?
SkullereQ
SkullereQOP2w ago
well its more like i have to do that for my homework
mg
mg2w ago
i understand but stick with me as far as numbers go, is there a difference?
SkullereQ
SkullereQOP2w ago
no
mg
mg2w ago
and double is a numeric type so it just stores the numeric value passing 6 to Math.Round() just tells it how many digits to round to what you want is to display a certain number of digits and that's done by the format specifier
SkullereQ
SkullereQOP2w ago
ok im going to check the link and see if i can come up with a solution Console.WriteLine($"Decimal part = {number4:F6}"); change last line to this and it's working
mg
mg2w ago
there ya go
Matheus Giraldi
// Use a custom format string "0.000000" to ensure 6 decimal places. Console.WriteLine($"Decimal part = {number4.ToString("0.000000")}");

Did you find this page helpful?