I have a double value. I want to format this value in the format of x.yz. How do I do this? I keep getting digits truncated. Can someone tell me how to do this in C#?
Thanks!
Digits after decimal point
This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.
// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"
Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.
// max. two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"
Digits before decimal point
If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.
// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567); // "123.5"
String.Format("{0:00.0}", 23.4567); // "23.5"
String.Format("{0:00.0}", 3.4567); // "03.5"
String.Format("{0:00.0}", -3.4567); // "-03.5"
Thousands separator
To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.
String.Format("{0:0,0.0}", 12345.67); // "12,345.7"
String.Format("{0:0,0}", 12345.67); // "12,346"
Zero
Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).
Following code shows how can be formatted a zero (of double type).
String.Format("{0:0.0}", 0.0); // "0.0"
String.Format("{0:0.#}", 0.0); // "0"
String.Format("{0:#.0}", 0.0); // ".0"
String.Format("{0:#.#}", 0.0); // ""
Align numbers with spaces
To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not in double.ToString method). To align numbers to the left use negative number of spaces.
String.Format("{0,10:0.0}", 123.4567); // " 123.5"
String.Format("{0,-10:0.0}", 123.4567); // "123.5 "
String.Format("{0,10:0.0}", -123.4567); // " -123.5"
String.Format("{0,-10:0.0}", -123.4567); // "-123.5 "
Custom formatting for negative numbers and zero
If you need to use custom format for negative float numbers or zero, use semicolon separator „;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.
String.Format("{0:0.00;minus 0.00;zero}", 123.4567); // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567); // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0); // "zero"
http://www.csharp-examples.net/string-format-double/
Using format strings is explained in:
Standard Numeric Format Strings
Custom Numeric Format Strings
For example, try:
(0.56789).ToString("F2")
(0.56789).ToString("0.00").
Note that the resulting value is NOT truncated, but rounded in both cases, resulting in "0.57".
string.Format("{0:0.00}",yourdouble);
And maybe you'll find useful stick a paper with this http://john-sheehan.com/blog/wp-content/uploads/msnet-formatting-strings.pdf somewhere in your office
Tried something like this, using ToString?
doubleNumber = -1898300.1937;
Console.WriteLine(doubleNumber.ToString("F2", CultureInfo.InvariantCulture));
// Displays -1898300.19
I'm using Math.Round Method
Math.Round(yourdouble, 2)
You can also specify the rounding rule.
Try this:
number.ToString("0.00");
Also take a look at Custom Numeric Format Strings
Related
I need to keep track of the number of significant digits in a number (float or integer). Trailing zeroes after a decimal point are considered significant, e.g. in 12.0 there are 3 significant figures and in 12.00 there are 4. I thought to use something like len(str(number)) but this removes all but one of the trailing zeroes from floats. The format() function and str.format() method, often suggested for similar questions (in integer, in float, and float again) would both seemingly require me to know in advance how many decimal points I wanted. Is there a good way to go about this? Should I just require the number to be inputted as a string so that all trailing zeroes are preserved? The code I'm using to find significant figures is below. I believe that it works for all cases except that described above.
def __init__(self, value):
"""Initializes a Sigfig object with the given value and finds the number of significant figures in value"""
assert type(value)==int or type(value)==float or type(value)==Sigfig, "Sigfig value must be of type int, float, or Sigfig"
# I wanted to avoid values of type str so that I don't have to worry about inputs like Sigfig('55b')
self.value=value #This is to allow math with full value to avoid losing precision to rounding
self.valuestring=f'{value}'
#Remove leading zeroes before or after a decimal point and scientific notation
self.remlead0enot=self.valuestring.lstrip('0').lstrip('.').lstrip('0').split('e',1)[0]
#Account for ambiguous zeroes before implied decimal point e.g. 1000
if '.' not in self.valuestring and self.valuestring[-1]=='0':
self.sigfigs=len(self.remlead0enot.rstrip('0'))
#Account for floats e.g. 1.005 and ints e.g. 105
else:
self.sigfigs=len(self.remlead0enot)-1 if '.' in self.remlead0enot else len(self.remlead0enot)
I'm not sure what you want to achieve but if if your question is if you can make a float remember with how many trailing zeros it was stored with: No.
You can only define how many points after the comma should be included when you convert the float to a string. But the float itself has no concept about significant digits. (Aka: 3.000000f == 3.0f)
If you need to know the amount of trailing zeros, yes, you need the input to be a string.
When you already have a string though you can also just store how many numbers are after the ..
arg_as_str = "3.100"
decimal_points = len(arg.split(".")[1]) # 3
as_float = float(arg) # 3.1
...
output_as_str = f"{as_float:{decimal_points}f}" # "3.100"
Hope that was helpful.
You can look into the package mpmath. This package is made specifically for this purpose, to allow arbitrary precision of floats.
https://mpmath.org/
I want to convert an integer to a hex string with a fixed length of 64 characters, prepended with zeros for integer values that do not use up all 32 hex values. If I try the following it adds spaces in front of s rather than zeros.
i := 898757
s := fmt.Sprintf("%64x", i)
fmt.Println(s)
The correct format is "%064x":
fmt.Printf("%064x\n", 898757)
00000000000000000000000000000000000000000000000000000000000db6c5
Where the leading 0 is a "flag" for the formatting string. Per the fmt docs:
0: pad with leading zeros rather than spaces;
for numbers, this moves the padding after the sign
My personal preference is to use a period to separate the flags from the length field. This technically works because . is not meaningful with the integer verbs and is ignored. I find it a useful visual indicator. The format string becomes "%0.64x".
I have this string: "123,456.39213212"
I would like to to be converted to a float and rounded UP to the 4th decimal place.
According to an online tool I used I should get this number: 123456.3922
Please advise how I can do this in Groovy?
Thanks
It feels a bit hacky, but if your thousands separator is always , you can do something like this:
import java.math.RoundingMode
def input = "123,456.39213212"
def output = new BigDecimal(input.replaceAll(",", "")).setScale(4, RoundingMode.UP)
Output:
123456.3922
Key parts are:
Replacing the comma with "" to have the string in a format that BigDecimal can work with and
Setting the scale to 4 using RoundingMode.UP (note: depending on your requirements regarding negative numbers you may want to use RoundingMode.CEILING instead)
Example Code:
GraphicsWindow.MouseDown = md
Sub md
color = GraphicsWindow.GetPixel(GraphicsWindow.MouseX,GraphicsWindow.MouseY)
EndSub
This returns a hexadecimal value, but I need to convert this to an rgb value. How do I do so?
The trick to the conversion is dealing with those pesky letters. I have found the easiest way to do this is with a "Map" structure where you equate the hex digits to decimal values. Small Basic makes this extra easy as array's in Small Basic are actually implemented as maps.
I worked up a full example based on your snippet above. You can get it using this Small Basic import code: CJK283
The subroutine below is the important bit. It converts a two digit hex number into its decimal equivalent. It also underscores how limited subroutines are in Small Basic. Rather than a single line for each call as you would see in other languages, where a parameter is passed in and a value is returned, in Small Basic this requires juggling variables inside the subroutine and at least three lines to call the subroutine.
'Call to the ConvertToHex Subroutine
hex = Text.GetSubText(color,2,2)
DecimalFromHex()
red = decimal
Convert a Hex string to Decimal
Sub DecimalFromHex
'Set an array as a quick and dirty way of converting a hex value into a decimal value
hexValues = "0=0;1=1;2=2;3=3;4=4;5=5;6=6;7=7;8=8;9=9;A=10;B=11;C=12;D=13;E=14;F=15"
hiNibble = Text.GetSubText(hex,1,1) 'The high order nibble of this byte
loNibble = Text.GetSubText(hex,2,1) 'The low order nibble of this byte
hiVal = hexValues[hiNibble] * 16 'Combine the nibbles into a decimal value
loVal = hexValues[loNibble]
decimal = hiVal + loVal
EndSub
Where would I insert this in my code? I have a inputs and a message box that I need to get to two decimals but I can't figure out where I should put it.
If you don’t want to print out the String and just want to format it for later use, you can use the static format method of the String class.
It works in exactly the same way as printf as far as formatting is concerned, but it doesn’t print the String, it returns a new formatted String.
String.format "%[argument number] [flags] [width] [.precision] type"
"%" is a special character in formatted String and it denotes start of formatting instruction. String.format() can support multiple formatting instruction with multiple occurrence of "%" character in formatting instruction.
"argument number" is used to specify correct argument in case multiple arguments are available for formatting.
"flags" is another special formatting instruction which is used to print String in some specific format for example you can use flag as "," to print comma on output.
"width" formatting option denotes minimum number or character will be used in output but in case if number is larger than width then full number will be displayed but if its smaller in length then it will be be padded with zero.
"precision" is using for print floating point formatted String, by using precision you can specify till how many decimal a floating point number will be displayed in formatted String.
"type" is the only mandatory formatting option and must always comes last in format String also input String which needs to be formatted must be with same type specified in "type" parameter.
public class StringFromatExample {
public static void main(String[] args) {
String s1 = String.format("%-4.5f %.20f", 35.23429837482,5.2345678901);
System.out.println(s1);
}
}
the output will be
35.23430 5.23456789010000000000