简体   繁体   English

我需要将小数或货币转换为整数

[英]I need to convert decimal or money to int

I try to convert this number to int in C#, but I can't. 我尝试在C#中将此数字转换为int ,但是我不能。

800,000.00 is the original number, I need 800000 . 800,000.00是原始数字,我需要800000

I used that line, but it didn't work. 我用了那条线,但是没有用。

value = int.Parse(Txt_proyeccion.Text, NumberStyles.Any | NumberStyles.Number);

That original number is in a textbox in asp app. 该原始号码在ASP应用程序的文本框中。

thanks! 谢谢!

Try doing it in two steps: 尝试分两个步骤进行:

  1. Parse to decimal . 解析为decimal

  2. Cast to int (truncate or round). 强制转换为int (截断或舍入)。

For instance 例如

// truncate: 80.97 -> 80
int value = (int) decimal.Parse(Txt_proyeccion.Text, NumberStyles.Any);

// round: 80.97 -> 81
int value = (int) Math.Round(decimal.Parse(Txt_proyeccion.Text, NumberStyles.Any));

Edit: You may want to specify format (eg CultureInfo.InvariantCulture ) in order to be sure that . 编辑:您可能想要指定格式 (例如CultureInfo.InvariantCulture ),以确保. is the decimal separator while , is the thousand separator: 小数点分隔符,而是是千位分隔符:

using System.Globalization;

...

// truncate: 80.97 -> 80
int value = (int) decimal.Parse(
  Txt_proyeccion.Text, 
  NumberStyles.Any,
  CulureInfo.InvariantCulture);

// round: 80.97 -> 81
int value = (int) Math.Round(decimal.Parse(
  Txt_proyeccion.Text, 
  NumberStyles.Any,
  CulureInfo.InvariantCulture));

Why on earth people are converting to string and back to a number I have no idea. 为什么地球上的人们会转换为字符串然后再转换为数字,我不知道。

float cash = 800000.49;
int number = (int)cash;

OR 要么

int number = (int)Math.Floor(cash);

OR 要么

int number = (int) Math.Round(cash);

You get the idea. 你明白了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM