用浮点数格式化数字并在 C# 中登录文本框

Format numbers with floating points and sign in textbox in C#(用浮点数格式化数字并在 C# 中登录文本框)
本文介绍了用浮点数格式化数字并在 C# 中登录文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个垂直左对齐的文本框.它们显示带有浮点数和符号的数字.数字在不断变化.我想固定浮点的位置,以便在更改数字时浮点的位置保持不变,并在所有文本框中保持垂直对齐.

I have multiple textboxes left-aligned vertically. They show numbers with floating points and signs. The numbers are continuously changing. I'd like to make the position of the floating point fixed so that when the numbers are changed the position of the floating points are unchanged and keep aligned vertically in all of the textboxes.

这是我尝试过的:

            textbox1.Text = number1.ToString("#000.00000");
            textbox2.Text = number2.ToString("#000.00000");
            textbox3.Text = number3.ToString("#000.00000");
            textbox4.Text = number4.ToString("#000.00000");

当数字为负数并且我看到 - 开始时,它可以工作,但是当它们为正数时,数字会向左移动.我可以手动在正数的开头添加空格或 + 号,但我想知道是否有更优雅的方法.此外,当数字像 3.2 时,这会将它们更改为 003.20000,是否有办法将额外的零更改为空格?

It works when the numbers are negative and I see - sign in the beginning, but when they are positive the numbers are shifted to the left. I can manually add space or + sign to the beginning of the positive numbers, but I am wondering if there a more elegant approach for this. Also when the numbers are like 3.2, this will change them to 003.20000, Is there anyway to make it so that the additional zeros are changed to space?

推荐答案

这应该可以解决问题:

textbox1.Text = String.Format("{0,10:+0.00000;-0.00000}", number1);
textbox2.Text = String.Format("{0,10:+0.00000;-0.00000}", number2);
textbox3.Text = String.Format("{0,10:+0.00000;-0.00000}", number3);
textbox4.Text = String.Format("{0,10:+0.00000;-0.00000}", number4);
textbox5.Text = String.Format("{0,10:+0.00000;-0.00000}", number5);

或者如果你想要在填充之前的符号符号.

or this if you want the sign symbol before the padding.

textbox1.Text = String.Format("{0:+;-}{0,9:0.00000;0.00000}", number1);
textbox2.Text = String.Format("{0:+;-}{0,9:0.00000;0.00000}", number2);
textbox3.Text = String.Format("{0:+;-}{0,9:0.00000;0.00000}", number3);
textbox4.Text = String.Format("{0:+;-}{0,9:0.00000;0.00000}", number4);
textbox5.Text = String.Format("{0:+;-}{0,9:0.00000;0.00000}", number5);

这篇关于用浮点数格式化数字并在 C# 中登录文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)