Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toFixed function in c#

Tags:

in Javascript, the toFixed() method formats a number to use a specified number of trailing decimals. Here is toFixed method in javascript

How can i write a same method in c#?

like image 732
Minh Nguyen Avatar asked Aug 04 '11 09:08

Minh Nguyen


People also ask

What is the toFixed () function used for?

The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals.

Is toFixed a string?

In JavaScript, toFixed() is a Number method that is used to convert a number to fixed-point notation (rounding the result where necessary) and return its value as a string. Because toFixed() is a method of the Number object, it must be invoked through a particular instance of the Number class.

Why is toFixed not working?

The "toFixed is not a function" error occurs when the toFixed() method is called on a value that is not a number . To solve the error, either convert the value to a number before calling the toFixed method or only call the method on numbers.

How do I return a number to toFixed?

The method toFixed(n) rounds the number to n digits after the point and returns a string representation of the result. We can convert it to a number using the unary plus or a Number() call, e.g write +num. toFixed(5) .


2 Answers

Use the various String.Format() patterns.

For example:

int someNumber = 20; string strNumber = someNumber.ToString("N2"); 

Would produce 20.00. (2 decimal places because N2 was specified).

Standard Numeric Format Strings gives a lot of information on the various format strings for numbers, along with some examples.

like image 91
Tim Avatar answered Sep 28 '22 23:09

Tim


You could make an extension method like this:

using System;  namespace toFixedExample {     public static class MyExtensionMethods     {         public static string toFixed(this double number, uint decimals)         {             return number.ToString("N" + decimals);         }     }      class Program     {         static void Main(string[] args)         {             double d = 465.974;             var a = d.toFixed(2);             var b = d.toFixed(4);             var c = d.toFixed(10);         }     } } 

will result in: a: "465.97", b: "465.9740", c: "465.9740000000"

like image 40
Răzvan Flavius Panda Avatar answered Sep 29 '22 01:09

Răzvan Flavius Panda